在Express后端执行重定向会更容易。
说你对/search/query
路径代码最初是这样的:
app.get("/search/query", function (req, res) {
// Do your query validation and fetch your search result.
// Here, I just check if a query value was given or not for the q param.
// I recommend you use better ways to check for empty queries.
// (ex: lodash's `isEmpty()` function)
if (req.query.q) {
// Serve the page !
res.send("What you want to render if the search result finds something.");
}
else {
// Return an error !
res.status(404).send("Nothing was found with the criterias entered.");
}
});
这可能是类似于你有什么。现在,这里是回答你的问题,根据上述初步实现:
app.get("/search/query", function (req, res, next) {
// Check if a query value was given AND if the value isn't equal to "query".
// The later condition is to prevent infinite loops.
if (req.query.q && req.query.q !== "query") {
// Redirect using the value assigned to the q query param.
res.redirect("/search/" + req.query.q);
}
else {
// Since there is no query parameter named `q` in the request,
// we can be sure that `query` reffers to a search term.
next();
}
});
app.param("srchterm", function (req, res, next, value) {
// Check, for example, if the value isn't empty.
if (value) {
// Do your query validation and fetch your search result HERE.
// Add those results in an array in the res.locals object.
// Those results can be used later.
res.locals.results = ["all", "your", "search", "results"];
}
next();
});
app.get("/search/:srchterm", function (req, res) {
console.log("another blah");
// We don't need to fetch the data here anymore, since it's handled by the param parser above!
// However, it's still necessary to check if the search gave back some results.
if (res.locals.results) {
// Serve the results !
res.send("A total of " + res.locals.results.length + " results were found for " + req.params['srchterm']);
}
else {
// Return an error !
res.status(404).send("Nothing was found with the criterias entered.");
}
});
从现在开始
因此,使用/search/query?q=123
每个查询将朝着/search/123
重定向。它甚至可以让您使用query
作为搜索词!
您的解决方案不能解决问题。当你确实有有用的代码时,重定向应该转到'/ search/query?= 123'而不是'/ search/123'。我发现另一种解决这个问题的方法。 – fauverism
我知道,我在回答他的解决方案后发现它完全相反。如果你愿意的话给我打个电话,但我确实相信,如果问题以一种不太令人困惑的方式提出,我可以正确回答;通常情况下,你需要定义程序的初始状态,然后提到你想要达到的目标,而不是相反。 – DiglidiDudeNG