Node.js 引用错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17508815/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 14:57:55  来源:igfitidea点击:

Node.js ReferenceError

node.js

提问by JasonStockman

This is my first go at NodeJS. I've installed it successfully on an instance at DigitalOcean.

这是我第一次接触 NodeJS。我已经在 DigitalOcean 的一个实例上成功安装了它。

I have the following helloworld.js

我有以下 helloworld.js

require("http");

http.createServer(function(request, response) {
response.writeHead(200, {"Content-Type": "text/plain"});
response.write("Hello World");
response.end();
}).listen(8888);console.log('Hello world');

When I run it via "node helloworld.js", I get the following error:

当我通过“node helloworld.js”运行它时,出现以下错误:

/home/jason/helloworld.js:4
http.createServer(function(request, response) {
^
ReferenceError: http is not defined
at Object.<anonymous> (/home/jason/helloworld.js:4:1)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
at node.js:901:3
jason@do:~$

Can someone point me in the right direction?

有人可以指出我正确的方向吗?

回答by c.P.u1

require()doesn't work like #includeor importdoes in other languages.

require()不喜欢的工作#includeimport做其他语言。

require() returns a reference to the resolved module. That reference must be assigned to a variable.

require() 返回对解析模块的引用。该引用必须分配给一个变量。

var http = require('http'); //the variable doesn't necessarily have to be named http
http.createServer(function(req, res) {});

Or

或者

require('http').createServer(function(req, res) {
});

回答by SLaks

As the error clearly states, there is no refunction.

正如错误明确指出的那样,没有任何re功能。

Do you mean require?

你的意思是require

回答by Maninder

I was also getting same problem and I have tried this:

我也遇到了同样的问题,我试过这个:

var http = require('http');
http.createServer(function (request, response) {

   response.writeHead(200, {'Content-Type': 'text/plain'});

   response.end('Server started\n');
}).listen(8081);

console.log('Server running at http://127.0.0.1:8081/');

May be it will help you.

也许它会帮助你。