当我在Node.js中要求http模块时,程序不会执行。

huangapple go评论52阅读模式
英文:

When i require http module in node js it will not execute the program

问题

I have the following code, whenever I run this file with node myserver.js. Then the program just seems to hang or something.

const http = require("http");

const server = http.createServer((req, res) => {
    res.end("Hello World");
});

server.listen(8000, "localhost");

I'm trying to get the output on port number 8000. But the program is not running even there is no error in the program. Maybe it's taking too much time for running. I also waited for it 10 minutes, but nothing would happen. I don't know what's going wrong here, it will just stop or just hang or something like below.

当我在Node.js中要求http模块时,程序不会执行。

英文:

I have the following code, whenever, I run this file with node myserver.js. Then the program just seems to hang or something.

const http = require("http");

const server = http.createServer((req, res) => {
    res.end("Hello World");
});

server.listen(8000, "localhost");

I'm trying to get the output on port number 8000. But the program is not running even there is no error in the program. Maybe it's taking too much time for running. I also waited for it 10 minutes, but nothing would happen. I don't know what's going wrong here, it will just stop or just hang or something like below.
当我在Node.js中要求http模块时,程序不会执行。

答案1

得分: 2

程序已经在运行!!!

该程序是在端口8000上运行的Web服务器,每当收到请求时都会返回Hello World

您可以通过运行程序、打开Chrome(或任何浏览器、Postman等),然后访问http://localhost:8000来验证这一点。

您还可以向server.listen()方法添加回调,以便让您知道服务器现在正在侦听。

像这样

server.listen(8080, "localhost", () => {
  console.log("Server started on 8080");
})

请注意,这不是必需的,只是一个确认,让您知道服务器正在运行。

P.S. - 对于server.listenlocalhost参数实际上并不是必需的。因为它默认已被使用。

英文:

The program is already running!!!

The program is a Web server running on port 8000 which returns Hello World whenever a request is received.

You can validate this by running the program, opening up Chrome (or any browser, Postman etc), and then hitting url http://localhost:8000

You can also add a callback to the server.listen() method which lets you know that the server is now listening.

Like

server.listen(8080, "localhost", () => {
  console.log("Server started on 8080");
})

Note that, this is not required and is just a confirmation for you to know that the server is running.

P.S. - The localhost argument to server.listen is not really required. Since it is taken by default

huangapple
  • 本文由 发表于 2023年5月17日 14:39:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/76269180.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定