Modifying Express.js Request Object

前端 未结 5 2078
既然无缘
既然无缘 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:18

    You can extend the express.request prototype.

    0 讨论(0)
  • 2021-01-01 09:33

    The best way to modify the request object is to add your own middleware function before the app.router declaration.

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

    This will modify the request object and every route will be able to access req.root property, so

        app.get('/',function(req, res, next){
          console.log(req.root); // will print "Whatever I want";
        });
    
    0 讨论(0)
  • 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);
    
    0 讨论(0)
  • 2021-01-01 09:40

    You can use a middleware. Add this to your app.configure block:

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

    Every request will go tough this function, and afterwards go to the right url-block thanks to next().

    0 讨论(0)
  • 2021-01-01 09:42

    The response object support custom variables in res.locals. See http://expressjs.com/en/4x/api.html#res.locals

    This is particularly useful for typescript users. The locals property is typed Record<string, any>

    0 讨论(0)
提交回复
热议问题