Было бы проще сделать перенаправление на back-end 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