Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
570 views
in Technique[技术] by (71.8m points)

node.js - Modifying Express.js Request Object

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...