1

When I try to start following script:

var http = require("http");

http.createServer(function(request, response) {
  response.writeHead(200, {"Content-Type": "text/plain"});
  response.write("Hello World");
  response.end();
}).listen(8000);

var ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress;

console.log(ip)

I get following Error:

node.js:201
        throw e; // process.nextTick error, or 'error' event on first tick
              ^
ReferenceError: req is not defined
    at Object.<anonymous> (/home/ubuntu/IPDeliverer/server.js:9:10)
    at Module._compile (module.js:441:26)
    at Object..js (module.js:459:10)
    at Module.load (module.js:348:32)
    at Function._load (module.js:308:12)
    at Array.0 (module.js:479:10)
    at EventEmitter._tickCallback (node.js:192:41)

My first guess was, that there is some module missing, so I installed the following module like this:

npm install req

and then I included following line

var req = require("./node_modules/req/node_modules/request");

but it is still not working. Any suggestions ?

2
  • Show the current source, what module you think you're using, etc. It's not clear why you'd be trying to get headers outside of any connection, though. Commented Aug 1, 2014 at 13:39
  • You probably mismatched the frameworks. Pure HTTP has request in handler specified in createServer. req is specific for the Express framework. So move your IP checking into that callback (keep in mind Node code is often async). Commented Aug 1, 2014 at 13:40

2 Answers 2

11

You've named the Request request, not req, also every callback has it's own request, so checking the IP outside the callback like that doesn't make sense. Use request inside the callback instead:

var http = require("http");

http.createServer(function(request, response) {
  response.writeHead(200, {"Content-Type": "text/plain"});
  response.write("Hello World");
  response.end();

  var ip = request.headers['x-forwarded-for'] || request.connection.remoteAddress;

  console.log(ip)
}).listen(8000);
Sign up to request clarification or add additional context in comments.

Comments

2

The variable req is not defined there. You have to move it inside of a request handler. Try this:

var http = require("http");

http.createServer(function(request, response) {
  var ip = request.headers['x-forwarded-for'] || request.connection.remoteAddress;

  console.log(ip)
  response.writeHead(200, {"Content-Type": "text/plain"});
  response.write("Hello World");
  response.end();
}).listen(8000);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.