【问题标题】:Can Express alter incoming requests and redirect to a different method after alteration?Express 可以更改传入的请求并在更改后重定向到不同的方法吗?
【发布时间】:2013-03-05 17:16:29
【问题描述】:

我有一个 Express (v3) 应用程序,其中(在理想情况下)用户在输入字段中键入字符串,等待自动完成函数返回与字符串匹配的列表,然后从该列表中进行选择,从而添加一个'id' 值到隐藏字段。当他们点击“Go”时,他们的请求将通过他们的查询路由到此端点:

app.get('/predict', function(req, res) {

  // req.query should be something like
  // { name: "wat", id: 123 }

  res.render('predictions');
}

我想稍微改变一下这个功能,这样如果 req.query.id 为空(即用户没有等待自动完成),我不必将它们重定向回来说“请等待自动完成”。

在我看来,我想扩展上述端点来做类似的事情

app.get('/predict', function(req, res) {

  // req.query is { name: 'wat', id: '' }

  if(req.query.id=='') {
    // then the user didn't wait for the autocomplete, so
    // guess the id ourselves
  } else {
    // ... some code
    res.render('predictions');
  }
}

在为自己猜测 ID 时,我使用的外部 API 与用于自动完成功能的 API 相同,该 API 根据查询参数返回具有置信度值的结果数组,即它认为结果是什么的可能性有多大我要。

现在我们来回答这个问题。我可以这样做吗?

app.get('/predict', function(req, res) {

  // req.query is { name: 'wat', id: '' }

  if (req.query.id=='') {

    makeRequestToAPIWithQuery(req.query.name, function(err, suggestions) {

      // suggestions[0] should contain my 'best match'
      var bestMatchName = suggestions[0].name;
      var bestMatchId   = suggestions[0].id;

      // I want to redirect back to *this* endpoint, but with different query parameters
      res.redirect('/predict?name='+bestMatchName+'&id='+bestMatchId);
    }
  } else {
    // some code
    res.render('predictions');
  }
}

如果 req.query.id 为空,我希望服务器向自身发出不同的请求。所以重定向后,req.query.id 不应该为空,res 会根据需要呈现我的“预测”视图。

这可能/明智/安全吗?我错过了什么吗?

非常感谢。

【问题讨论】:

    标签: node.js express response.redirect


    【解决方案1】:

    express 路由器接受多个处理程序作为中间件。

    您可以在第一个处理程序中测试id 的存在并相应地填充您的请求对象,然后在原始处理程序中没有发生任何事情。

    function validatePredictForm(req, res, next) {
      if(!req.query.id) {
        req.query.id = 'there goes what your want the default value to be';
        return next();
      }
      else {
        // everything looks good
        return next();
      }
    }
    
    app.get('/predict', validatePredictForm, function(req, res) {
    
      // req.query should be something like
      // { name: "wat", id: 123 }
    
      res.render('predictions');
    });
    

    【讨论】:

    • 感谢您的快速响应,您能举例说明如何实现吗?
    猜你喜欢
    • 1970-01-01
    • 2011-05-31
    • 2017-08-04
    • 2015-12-19
    • 1970-01-01
    • 2020-01-06
    • 1970-01-01
    • 2016-06-11
    • 2013-12-13
    相关资源
    最近更新 更多