Forward request to alternate request handler instead of redirect

前端 未结 7 2212
借酒劲吻你
借酒劲吻你 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:08

    Express 4+ with nested routers

    Instead of having to use the outside of route/function app, you can use req.app.handle

    "use strict";
    
    const express = require("express");
    const app = express();
    
    //
    //  Nested Router 1
    //
    const routerOne = express.Router();
    
    //  /one/base
    routerOne.get("/base", function (req, res, next) {
      res.send("/one/base");
    });
    
    //  This routes to same router (uses same req.baseUrl)
    //  /one/redirect-within-router -> /one/base
    routerOne.get("/redirect-within-router", function (req, res, next) {
      req.url = "/base";
      next();
    });
    
    //  This routes to same router (uses same req.baseUrl)
    //  /one/redirect-not-found -> /one/two/base (404: Not Found)
    routerOne.get("/redirect-not-found", function (req, res, next) {
      req.url = "/two/base";
      next();
    });
    
    //  Using the full URL
    //  /one/redirect-within-app -> /two/base
    routerOne.get("/redirect-within-app", function (req, res, next) {
      req.url = "/two/base";
    
      // same as req.url = "/one/base";
      //req.url = req.baseUrl + "/base";
    
      req.app.handle(req, res);
    });
    
    //  Using the full URL
    //  /one/redirect-app-base -> /base
    routerOne.get("/redirect-app-base", function (req, res, next) {
      req.url = "/base";
      req.app.handle(req, res);
    });
    
    
    
    //
    //  Nested Router 2
    //
    const routerTwo = express.Router();
    
    //  /two/base
    routerTwo.get("/base", function (req, res, next) {
      res.send("/two/base");
    });
    
    //  /base
    app.get("/base", function (req, res, next) {
      res.send("/base");
    });
    
    
    //
    //  Mount Routers
    //
    app.use("/one/", routerOne);
    app.use("/two/", routerTwo);
    
    
    //  404: Not found
    app.all("*", function (req, res, next) {
      res.status(404).send("404: Not Found");
    });
    

提交回复
热议问题