node.js 节点“未定义请求”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25081539/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Node "req is not defined"
提问by BoHyman Horseman
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 ?
但它仍然无法正常工作。有什么建议 ?
回答by Paul
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 requestinside the callback instead:
您已将 Request 命名为 Request request,而不是req,而且每个回调都有它自己的request,因此像这样检查回调之外的 IP 没有意义。request改为在回调中使用:
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);
回答by piergiaj
The variable req is not defined there. You have to move it inside of a request handler. Try this:
变量 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);

