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 ?
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);
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);