Node.js怎么搭建HTTP服务器

在 Node.js 中搭建一个简单的 HTTP 服务器非常容易。以下是一个基本的示例,演示如何使用 Node.js 创建一个简单的 HTTP 服务器:

// 导入 http 模块 const http = require('http');

// 创建一个 HTTP 服务器

const server = http.createServer((req, res) => {

// 设置响应头

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

// 发送响应内容

res.end('Hello, World!\n');

});

// 监听特定端口

const port = 3000;

server.listen(port, () => {

console.log(`Server is running on http://localhost:${port}`);

});

在这个示例中,我们使用 Node.js 的 http 模块来创建一个 HTTP 服务器。createServer 方法接受一个回调函数,这个回调函数会在每次有请求时被调用。在回调函数中,我们可以设置响应头、发送响应内容,并使用 res.end() 结束响应。

然后,我们使用 listen 方法来指定服务器监听的端口。在这个例子中,服务器会在端口 3000 上监听。当服务器启动后,你可以在浏览器中访问 http://localhost:3000,应该会看到 "Hello, World!"。

猜你喜欢

转载自blog.csdn.net/JttiSEO/article/details/132452204