Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nodejs express: hostname with port from the req object

Sometimes I want to sent a qualified URL in a mail from my node application. Or I would like to set the content of a phantom page object.

I get the full URL like this in my deployment setup.

'http://' + req.hostname + '/myapp'

However on the development machine this usually produces:

http://localhost/myapp instead off http://localhost:3000/myapp

I know how to get the port but I don't want to use something like:

'http://' + req.hostname + ':' + port + '/myapp'

Which would produce nonsense like this in deploy behind a proxy.

http://domain.com:3000/myapp

Is there a smart way to get the hostname with port from the request object if the app runs outside a proxy?

like image 830
Dennis Bauszus Avatar asked Mar 10 '23 23:03

Dennis Bauszus


1 Answers

I'm not sure why Express Request deprecated host, but this is a safe bit of code to overcome the issue of running an Express server behind/not behind a proxy.

const proxyHost = req.headers["x-forwarded-host"];
const host = proxyHost ? proxyHost : req.headers.host;

(Where I have found this most handy is constructing "return to" URLs for workflows involving redirects eg: OAuth 2)

like image 155
kierans Avatar answered Mar 20 '23 13:03

kierans