When I try to start following script:
var http = require(\"http\");
http.createServer(function(request, response) {
response.writeHead(200, {\"Content-Type\":
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);