I was looking into how to complete the Header parser project for Micro services, I hypothesized that writing a script as below would get me all the header information which it does but the object it returns to the client does not show the ‘x-forwarded-for’ key.
var express = require('express')
var app = express()
app.get('/', function (req, res) {
res.send(req.headers)
})
However when I write:
app.get('/', function (req, res) {
var ip = req.headers['x-forwarded-for'];
res.send({"ipaddress":ip})
})
I didn’t do this project myself. But judging from their docs you should use req.ip and also set trust proxy. Please, refer to the docs ‘API’ and look for req.ip. Also, on my local machine it returns “::1”. Explanation for that can be found here
Hope that helps.
Thanks! I have already completed the project, my question is more about express itself than the project. When I send req.headers I don’t see ‘x-forwarded-for’ but yet I can access it directly like req.headers[‘x-forwarded-for’]. This does not make sense to me.
What do you mean by access? I checked it with nodejs console, it returns undefined. The fact that you get empty object I think comes from the workings of JSON.stringify, express probably does something like this when sending you an object.
For example try it