0

I have multiple routers when using express(4.16.4) like this:

var app=express();

app.use("/item",ItemRouter)
app.use("/user",UserRouter)
.....

And I want to forward(not the client redirect) the request from ItemRouter to UserRouter:

ItemRouter.js:

var ItemRouter = express.Router();

ItemRouter.get("/xxx",(req,res,next)=>{
  // jump to /user/xxx
  next("route")
});

I register the ItemRouter before UserRouter. And The usage of next('route') is got by searching in google and sf. For example: Forward request to alternate request handler instead of redirect

This question meet the same problem, and there is an answser suggested three options:

Option 1: route multiple paths to the same handler function

Option 2: Invoke a separate handler function manually/conditionally

Option 3: call next('route')

And I prefer to option 3, since in my opinion each router should be separated and de-coupled.

However as shown, it does not work.

Did I miss anything?

hguser
  • 35,079
  • 54
  • 159
  • 293
  • What exactly are you trying to accomplish? What does `ItemRouter.get()` do that requires forwarding the request to another router? `next('route')` is typically meant to be used in middleware chains, not to forward requests to other routers (I don't even think it's _possible_ to use it for that purpose, to be honest). – robertklep Dec 03 '18 at 11:52
  • We have a service, and we need to provide different endpoints according to different specification based on the same service. Of course we can call the common/shared components in different routers for different specification. But we think forward is better. Since in my opinion, different specification endpoints are just wrappers. – hguser Dec 04 '18 at 02:07
  • I don't agree that forwarding is the correct solution. It obfuscates the request flow (if an outsider would read `next('route')`, they have no idea where the request is being forwarded to because it's highly unspecific), is prone to bugs (what if you introduce another router into the mix?), and `next('route')` isn't meant to be used like that. I think shared components, or middleware, is a better solution. – robertklep Dec 04 '18 at 06:57
  • I agree that `next('route')` is a bad idea. In fact I prefer the manner in jsp like `forward:/path` which will make it clear enough that where this request will be forwarded. – hguser Dec 04 '18 at 08:52

0 Answers0