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!"。

相关推荐
网络工程小王3 小时前
【LangGraph 子图(Subgraph)详解】学习笔记
java·服务器·数据库·人工智能·langchain
源远流长jerry4 小时前
Linux 网络性能优化:从应用到内核
linux·运维·服务器·网络·网络协议·性能优化
goyeer4 小时前
【ITIL】指导原则
linux·运维·服务器·数字化·itil
故事还在继续吗5 小时前
高性能网络
服务器·网络·c/c++
认真的薛薛5 小时前
阿里云: A记录 & CNAME
服务器·前端·阿里云
步十人5 小时前
【FastAPI】ORM-02.使用 ORM 高效处理数据库逻辑
服务器·数据库·fastapi
坚持就完事了5 小时前
Linux的ln命令
linux·运维·服务器
绿豆人5 小时前
操作系统上电后流程
linux·服务器
会周易的程序员5 小时前
aiDgeScanner架构与实现
c++·ide·物联网·架构·node.js·aiot
Tingjct6 小时前
Linux开发工具
linux·运维·服务器