43

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. For example:

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

I could of course concatenate req.protocol, req.host, and somehow pass around the port number (seems to be missing from the req object) for each one of my URI listeners, but I'd like to be able to do it in a way that all of them could access this information.

Also, the hostname can vary between request (the machine has multiple interfaces) so I can't just concatenate this string when the application launches.

The goal is to provide URI's to the consumer which point to further resources in this API.

Is there some sort of way to tell Express that I want req objects to have this additional information? Is there a better way to do this than what I'm outlining?

4

5 回答 5

74

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

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

用于req.get获取Host标头,如果需要,该标头应包括端口。

请务必在之前添加它:

app.use(app.router);
于 2012-09-20T18:13:49.417 回答
36

您可以扩展express.request原型。

于 2012-09-23T23:11:18.200 回答
8

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

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

这将修改请求对象,并且每个路由都可以访问req.root属性,所以

    app.get('/',function(req, res, next){
      console.log(req.root); // will print "Whatever I want";
    });
于 2012-09-20T18:12:50.267 回答
4

您可以使用中间件。将此添加到您的app.configure块中:

app.use(function (req, res, next) {
  req.root = 'WHAT YOU WANT';
  next();
});

每个请求都会执行此功能,然后通过next().

于 2012-09-20T18:13:12.507 回答
1

响应对象支持res.locals. 见http://expressjs.com/en/4x/api.html#res.locals

这对打字稿用户特别有用。该locals属性已键入Record<string, any>

于 2020-10-19T09:38:37.420 回答