节点" req未定义"

时间:2014-08-01 13:37:06

标签: node.js

当我尝试开始关注脚本时:

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)

我得到以下错误:

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)

我的第一个猜测是,缺少一些模块,所以我安装了以下模块:

npm install req

然后我包含以下行

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

但它仍然无效。有什么建议吗?

2 个答案:

答案 0 :(得分:8)

您已将请求request命名为req,而不是request,并且每个回调都有自己的request,因此请在回调之外检查IP,而不是{&1}} #39;理智。请在回调中使用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);

{{1}}

答案 1 :(得分:1)

那里没有定义变量req。您必须在请求处理程序中移动它。试试这个:

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