Express header x-forwarded-for

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 don’t get an error. What is going on?

Nothing gets back? It’s probably undefined. Do you see ‘x-forwarded-for’ property when you send req.headers?

When I send req.headers I don’t see it and my question is why. To me it seems that it should show up when I send the entire req.headers object.

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.

1 Like

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

JSON.stringify({ x: undefined}); // returns {}

Okay, I understand now. I was thinking like python dictionaries where if you access a dictionary like myDictionary[nonExistentKey] it raises an error.