修改Express.js请求对象

Tho*_* II 32 node.js express

在express.js中,我想为每个URI侦听器的请求对象提供一个附加属性.这将提供协议,主机名和端口号.例如:

app.get('/users/:id', function(req, res) {
  console.log(req.root); // https://12.34.56.78:1324/
});
Run Code Online (Sandbox Code Playgroud)

我当然可以连接req.protocol,req.host,并以某种方式传递我的每个URI侦听器的端口号(似乎从req对象中丢失),但我希望能够在一种方式,所有人都可以访问这些信息.

此外,主机名可以在请求之间变化(机器有多个接口),因此我不能在应用程序启动时连接此字符串.

目标是向消费者提供URI,指向此API中的更多资源.

是否有某种方式告诉Express我希望req对象有这些附加信息?有没有比我概述的更好的方法来做到这一点?

Jon*_*ski 56

您可以添加为每个请求设置属性的自定义中间件:

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

使用req.get获得Host头,其中应包括端口,如果需要它.

请务必先添加:

app.use(app.router);
Run Code Online (Sandbox Code Playgroud)


小智 35

您可以扩展express.request原型.


Dea*_*ady 7

修改请求对象的最佳方法是在app.router声明之前添加自己的中间件函数.

    app.use(function(req, res, next){
      // Edit request object here
      req.root = 'Whatever I want';
      next();
    });
    app.use(app.router);
Run Code Online (Sandbox Code Playgroud)

这将修改请求对象,并且每条路由都能够访问req.root属性,因此

    app.get('/',function(req, res, next){
      console.log(req.root); // will print "Whatever I want";
    });
Run Code Online (Sandbox Code Playgroud)