您有一个以express和angular创建的应用程序,允许用户执行搜索。 URL是基于刚刚执行的搜索构建的。因此,如果您对“Will”执行搜索,则网址看起来像http://localhost.com:9000/search/query?q=Will
一切正常,但您忘记了应用之前执行的搜索没有/query?=
,而现在所有旧链接都在{{1} }或http://localhost.com:9000/search/will
不再有效。
让旧链接再次运行的正确方法是什么?
您是否应该在前端使用JavaScript来查找/查询?=在URL中丢失并在搜索路径之后但在查询文本之前添加?
答案 0 :(得分:2)
在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
作为搜索词!
答案 1 :(得分:0)
只需使用正则表达式并重定向
app.use(function(req, res, next) {
var searchRegEx = /\/search/g;
var searchedTerm = req.originalUrl.replace(searchRegEx, '');
var queryPath = req.originalUrl.match(/\/query[?]q=/);
if(!queryPath) {
var regexSlash = /\//g;
res.redirect('query?q=' + searchedTerm.replace(regexSlash, ''));
}
else {
next();
}
});