在 Node.js 中使用 HTTP 服务器构建 HTTP 模块
Source: Dev.to

什么是 HTTP 模块?
http 模块是 Node.js 内置的库,用于创建 HTTP 服务器和处理网络请求。它提供对 HTTP 协议的低层访问,不带任何框架开销。
import http from 'http';
创建你的第一个 HTTP 服务器
createServer() 方法是你的入口点。它接受一个请求处理函数并返回一个服务器实例:
import http from 'http';
const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Hello from Node.js HTTP server!');
});
server.listen(3000, () => {
console.log('Server running on http://localhost:3000');
});
发生了什么
createServer()创建一个服务器,用于监听传入的 HTTP 请求。- 回调函数接收两个对象:
req(请求)和res(响应)。 listen(3000)将服务器绑定到 3000 端口。
理解请求和响应对象
请求对象 (req)
包含所有传入的请求数据:
const server = http.createServer((req, res) => {
console.log('Method:', req.method); // GET, POST, etc.
console.log('URL:', req.url); // /about, /api/users
console.log('Headers:', req.headers); // All request headers
res.end('Request logged');
});
响应对象 (res)
用于向客户端发送数据:
const server = http.createServer((req, res) => {
// 设置状态码和响应头
res.writeHead(200, {
'Content-Type': 'application/json',
'X-Custom-Header': 'MyValue'
});
// 发送响应体
res.end(JSON.stringify({ message: 'Success' }));
});
构建一个简单的路由器
手动处理不同的路由:
import http from 'http';
const server = http.createServer((req, res) => {
if (req.url === '/' && req.method === 'GET') {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end('
首页
’); } else if (req.url === ‘/api/users’ && req.method === ‘GET’) { res.writeHead(200, { ‘Content-Type’: ‘application/json’ }); res.end(JSON.stringify({ users: [‘Alice’, ‘Bob’] })); } else { res.writeHead(404, { ‘Content-Type’: ‘text/plain’ }); res.end(‘404 Not Found’); } });
server.listen(3000);
## 处理带有正文数据的 POST 请求
读取请求体需要处理数据流:
```js
import http from 'http';
const server = http.createServer((req, res) => {
if (req.url === '/api/data' && req.method === 'POST') {
let body = '';
req.on('data', chunk => {
body += chunk.toString();
});
req.on('end', () => {
const data = JSON.parse(body);
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ received: data }));
});
}
});
server.listen(3000);
关键要点
何时使用原生 HTTP 模块
- 学习 Node.js 基础和 HTTP 协议基础
- 使用最少的依赖构建微服务
- 在没有框架开销的情况下最大化性能
何时使用像 Express 这样的框架
- 复杂的路由和中间件需求
- 快速的应用开发
- 内置的安全特性和请求解析
最佳实践
- 始终设置适当的
Content-Type头部。 - 使用正确的状态码处理错误(例如 404、500)。
- 使用
res.end()完成响应。 - 考虑为生产环境的应用添加安全头部。
后续步骤
- 探索 Node.js 流,用于处理大文件上传。
- 了解
https模块,以支持 SSL/TLS。 - 在深入 Express.js 之前学习中间件模式。
掌握 http 模块为你提供了理解每个 Node.js 框架底层工作原理的基础——让你成为更高效的后端开发者。