用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。參數要求。路徑和其他請求屬性。


注意!

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



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