Modifying Express.js Request Object

前端 未结 5 2092
既然无缘
既然无缘 2021-01-01 09:14

In express.js, I would like to provide an additional attribute on the request object for each of my URI listeners. This would provide the protocol, hostname, and port number

5条回答
  •  余生分开走
    2021-01-01 09:38

    You can add a custom middleware that sets the property for each request:

    app.use(function (req, res, next) {
        req.root = req.protocol + '://' + req.get('host') + '/';
        next();
    });
    

    Using req.get to obtain the Host header, which should include the port if it was needed.

    Just be sure to add it before:

    app.use(app.router);
    

提交回复
热议问题