Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 386
Thomas Hunter II Avatar asked Sep 20 '12 17:09

Thomas Hunter II


People also ask

What is Express request object?

Introduction. Short for request , the req object is one half of the request and response cycle to examine calls from the client side, make HTTP requests, and handle incoming data whether in a string or JSON object. In this article, you will learn about the req object in Express.

Why is Express JS Unopinionated?

Express JS is minimal and unopinionated​Express uses less overhead in the core framework so that makes it minimal and a good choice for building out large web applications. You don't want to have a framework that fills your codebase with lots of bloatware that you are never gonna use.


1 Answers

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); 
like image 68
Jonathan Lonowski Avatar answered Sep 27 '22 23:09

Jonathan Lonowski