【问题标题】:Forward with query in express js在 express js 中使用查询转发
【发布时间】:2017-03-31 16:42:36
【问题描述】:

我尝试将一些请求转发给另一个处理程序:

route.get("/tag/:id",function(req,res,next){
  req.url="/posts?tag_id="+req.params.id
  next('route')
})

route.get("/posts",function(req,res,next){
  console.info(req.query);
})

query 在第二个处理程序中为空。

如何解决?

【问题讨论】:

  • 你为什么要那个?第一种选择,使用res.redirect(),其次在其他地方编写逻辑并在路由器中使用它。
  • @MukeshSharma Exatcly。在这些情况下,重定向更有意义。
  • 想想wordpress中的永久链接,你不能将/tag/x重定向到index.php?tag_name=x

标签: node.js express routes


【解决方案1】:

req.query 为空,因为您手动设置了 url,它不会再次被解析。

如果调用了第二个处理程序,但只有 req.query 未设置,则改为:

route.get("/tag/:id", function (req, res, next) {
  req.url = "/posts?tag_id=" + req.params.id;
  next('route');
});

你可以试试:

route.get("/tag/:id", function (req, res, next) {
  req.url = "/posts?tag_id=" + req.params.id;
  req.query = {tag_id: req.params.id}; // or whatever you want
  next('route');
});

或:

route.get("/tag/:id", function (req, res, next) {
  req.url = "/posts?tag_id=" + req.params.id;
  req.query = url.parse(req.url, true).query;
  next('route');
});

如果在您的处理程序中使用它,那么您可能还需要更新 req.paramsreq.pathother request properties

【讨论】:

  • 我使用req.query = url.parse(req.url, true).query,谢谢。
猜你喜欢
  • 2021-12-21
  • 1970-01-01
  • 1970-01-01
  • 2017-08-10
  • 2013-07-04
  • 1970-01-01
  • 1970-01-01
  • 2022-06-15
  • 2019-01-06
相关资源
最近更新 更多