如何在Node.js中创建HTTP服务器?
warning:
这篇文章距离上次修改已过192天,其中的内容可能已经有所变动。
在Node.js中创建HTTP服务器通常涉及使用内置的http
模块。以下是创建基本HTTP服务器的步骤和示例代码:
- 导入
http
模块。 - 使用
http.createServer()
方法创建一个新的HTTP服务器。 - 监听服务器的
request
事件以处理进入的请求。 - 定义响应回调函数,以发送响应。
示例代码:
const http = require('http'); // 导入http模块
// 创建HTTP服务器
const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/plain' }); // 设置响应头
res.end('Hello World\n'); // 发送响应内容
});
// 监听3000端口
server.listen(3000, () => {
console.log('服务器运行在 http://localhost:3000/');
});
运行上述代码后,打开浏览器并访问http://localhost:3000/
,你将看到输出“Hello World”。
评论已关闭