Forward request to alternate request handler instead of redirect

前端 未结 7 2140
借酒劲吻你
借酒劲吻你 2020-12-07 22:24

I\'m using Node.js with express and already know the existence of response.redirect().

However, I\'m looking for more of a forward() funct

7条回答
  •  执笔经年
    2020-12-07 23:04

    You just need to invoke the corresponding route handler function.

    Option 1: route multiple paths to the same handler function

    function getDogs(req, res, next) {
      //...
    }}
    app.get('/dogs', getDogs);
    app.get('/canines', getDogs);
    

    Option 2: Invoke a separate handler function manually/conditionally

    app.get('/canines', function (req, res, next) {
       if (something) {
          //process one way
       } else {
          //do a manual "forward"
          getDogs(req, res, next);
       }
    });
    

    Option 3: call next('route')

    If you carefully order your router patterns, you can call next('route'), which may achieve what you want. It basically says to express 'keep moving on down the router pattern list', instead of a call to next(), which says to express 'move down the middleware list (past the router)`.

提交回复
热议问题