Nodejs request.header dosnt exists

Highlight a lot of lessons, articles, and stackoverflow questions about getting a client IP address from NodeJS. Almost all of them use this request.header('x-forwarded-for') My NodeJS v0.8.7 does not have this request.header function.

typeof request.header returns undefined

However, I have request.headers, which is an object containing some information:

 { host: '127.0.0.1:8000', connection: 'keep-alive', accept: '*/*', 'user-agent': 'Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.89 Safari/537.1', 'accept-encoding': 'gzip,deflate,sdch', 'accept-language': 'en-US,en;q=0.8', 'accept-charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3' } 

The host value seems to be worth checking out. Running node on localhost clearly returned 127.0.0.1:8000 , but then I tried to access my node.js site from my netbook on the same network, pointing to 192.168.0.13 (my desktop IP address where node is running) and I got 192.168.0.13:8000 . Thus, it does not give me the client IP address, but what IP address is used to indicate the application.

I then tried request.connection.remoteAddress as it got the name from the tutorials that I found. Running from localhost gave 127.0.0.1 and from my netbook 192.168.0.12 . So it worked! 192.168.0.12 is the netbook IP address. But over the tutorials and questions that I found, they say that the right path will be the first, depending on whether your proxy is yours or not.

So what would be the right way to do this? and why does request.header not exist for me?

+6
source share
1 answer

If you are using express 3, you can do this:

 req.ip // => "127.0.0.1" 

http://expressjs.com/api.html#req.ip

If you want to use other headers, you can use this:

 req.get(field) req.get('Content-Type'); // => "text/plain" req.get('content-type'); // => "text/plain" req.get('Something'); // => undefined 

http://expressjs.com/api.html#req.get

If you are using a regular node, use this:

 request.headers 
+5
source

Source: https://habr.com/ru/post/926065/


All Articles