hguser hguser - 21 days ago 12
Node.js Question

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?

rsp rsp
Answer

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

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

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