简体   繁体   English

nodejs中的hello world,http未定义

[英]hello world in nodejs, http not defined

i tried to run a hello world command in nodejs, but something wrong have happened, could you help me?我试图在 nodejs 中运行一个 hello world 命令,但是发生了错误,你能帮我吗?

http.createServer(function(req, res){
  res.writeHead(200, {'Content-Type': 'text/plain' });
  res.end('Hello World \n');
}).listen(8080, '127.0.0.1');
~ $ node server.js
/data/data/com.termux/files/home/server.js:1
http.createServer(function(req, res){
^

ReferenceError: http is not defined
    at Object.<anonymous> (/data/data/com.termux/files/home/server.js:1:1)
    at Module._compile (node:internal/modules/cjs/loader:1101:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
    at Module.load (node:internal/modules/cjs/loader:981:32)
    at Function.Module._load (node:internal/modules/cjs/loader:822:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:79:12)
    at node:internal/main/run_main_module:17:47

You have not created a variable called http.您尚未创建名为 http 的变量。 Also you have to create few more things before you call that http.createserver function在调用 http.createserver 函数之前,您还必须创建更多的东西

const http = require('http');

const hostname = '127.0.0.1';
const port = 3000;

const server = http.createServer((req, res) => {
  res.statusCode = 200;
  res.setHeader('Content-Type', 'text/plain');
  res.end('Hello World');
});

server.listen(port, hostname, () => {
  console.log(`Server running at http://${hostname}:${port}/`);
});

This is the complete code you should use.这是您应该使用的完整代码。

Before having used the http module, you will have to import it first.在使用http模块之前,您必须先导入它。 Add the import statement before using it:使用前添加import语句:

let http = require("http");

Please make sure you have this statement written!请确保您已写下此声明!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM