node.js 修改 Express.js 请求对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12518132/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Modifying Express.js Request Object
提问by Thomas Hunter II
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:
在 express.js 中,我想为每个 URI 侦听器的请求对象提供一个附加属性。这将提供协议、主机名和端口号。例如:
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.
我当然可以连接 req.protocol、req.host,并以某种方式为我的每个 URI 侦听器传递端口号(req 对象中似乎缺少),但我希望能够在一种让所有人都可以访问这些信息的方式。
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.
目标是向消费者提供指向此 API 中更多资源的 URI。
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?
是否有某种方法可以告诉 Express 我希望 req 对象具有这些附加信息?有没有比我概述的更好的方法来做到这一点?
回答by Jonathan Lonowski
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.getto obtain the Hostheader, which should include the port if it was needed.
使用req.get获得Host头,其中应包括端口,如果需要它。
Just be sure to add it before:
请务必在之前添加它:
app.use(app.router);
回答by TJ Holowaychuk
You can extend the express.requestprototype.
您可以扩展express.request原型。
回答by DeadAlready
The best way to modify the request object is to add your own middleware function before the app.router declaration.
修改请求对象的最佳方式是在 app.router 声明之前添加自己的中间件函数。
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.rootproperty, so
这将修改请求对象,每个路由都将能够访问req.root属性,因此
app.get('/',function(req, res, next){
console.log(req.root); // will print "Whatever I want";
});
回答by Mattias
You can use a middleware. Add this to your app.configureblock:
您可以使用中间件。将此添加到您的app.configure块中:
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().
每个请求都会处理这个函数,然后由于next().

