Forward request to alternate request handler instead of redirect

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

    For Express 4+

    Using the next function does not work if the next handler is not added in the right order. Instead of using next, I use the router to register the handlers and call

    app.get("/a/path", function(req, res){
        req.url = "/another/path";
        app.handle(req, res);
    }
    

    Or for HTML5 mode of React/Angular

    const dir = process.env.DIR || './build';
    
    // Configure http server
    let app = express();
    app.use('/', express.static(dir));
    
    // This route sends a 404 when looking for a missing file (ie a URL with a dot in it)
    app.all('/*\.*', function (req, res) {
        res.status(404).send('404 Not found');
    });
    
    // This route deals enables HTML5Mode by forwarding "missing" links to the index.html
    app.all('/**', function (req, res) {
        req.url = 'index.html';
        app.handle(req, res);
    });
    

提交回复
热议问题