gpt4 book ai didi

node.js - Express 是否可以更改传入请求并在更改后重定向到不同的方法?

转载 作者:太空宇宙 更新时间:2023-11-03 23:10:24 24 4
gpt4 key购买 nike

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

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,该函数返回一个结果数组,其中包含基于查询参数的置信度值,即它认为结果是我想要的结果的可能性。

现在我们进入正题。我可以做这样的事情吗?

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 将根据需要呈现我的“预测” View 。

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

提前非常感谢。

最佳答案

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');
});

关于node.js - Express 是否可以更改传入请求并在更改后重定向到不同的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15230072/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com