Node “req is not defined”

后端 未结 2 1246
没有蜡笔的小新
没有蜡笔的小新 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);
    
    0 讨论(0)
  • 2021-01-27 12:34

    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);
    
    0 讨论(0)
提交回复
热议问题