可以快速改变传入的请求,并改变后redirect到一个不同的方法?

我有一个Express(v3)应用程序,在一个理想的情况下,用户在input字段中键入一个string,等待一个自动完成函数返回一个匹配string的列表,并从该列表中select,从而添加一个“id”价值隐藏的领域。 当他们点击“转到”时,他们的请求被路由到这个端点,并带有查询:

app.get('/predict', function(req, res) { // req.query should be something like // { name: "wat", id: 123 } res.render('predictions'); } 

我想稍微改变这个function,所以如果req.query.id是空的(即用户没有等待自动完成),我不必redirect他们说“请等待自动完成”。

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

 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,它使用基于查询参数的置信度值返回结果数组,即有多大可能认为结果是我想要的。

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

 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为空,我希望服务器对自己发出不同的请求。 所以在redirect之后,req.query.id不应该是空的,res将根据需要呈现我的“预测”视图。

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

非常感谢提前。

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

您可以testing第一个处理程序中是否存在该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'); });