用express js进行查询

[英]Forward with query in express js


I tried to forward some requests to another handler:

我试图将一些请求转发给另一个处理器:

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

The query is empty in the second handler.

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

How to fix that?

如何修复呢?

1 个解决方案

#1


3  

req.query is empty because you set the url manually and it doesn't get parsed again.

要求的事情。查询是空的,因为您手动设置url,并且不会再次解析它。

It the second handler is called but only the req.query is not set, then instead of:

它调用第二个处理器,但只调用req。查询未设置,则改为:

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

you can try:

你可以尝试:

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

or:

或者:

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

If it is used in your handlers then you may also need to update req.params, req.path and other request properties.

如果在处理程序中使用它,那么您可能还需要更新req。参数要求。路径和其他请求属性。

智能推荐

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:http://www.itdaan.com/blog/2016/11/17/7203531e3c89030ef819e9d37b576ab9.html



 
© 2014-2019 ITdaan.com 粤ICP备14056181号  

赞助商广告