Node “req is not defined”

后端 未结 2 1255
没有蜡笔的小新
没有蜡笔的小新 2021-01-27 11:33

When I try to start following script:

var http = require(\"http\");

http.createServer(function(request, response) {
  response.writeHead(200, {\"Content-Type\":         


        
2条回答
  •  故里飘歌
    2021-01-27 12:07

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

提交回复
热议问题