在 Node.js 中,http
模块是其核心模块之一,它为创建 HTTP 服务器和客户端提供了强大的功能。借助 http
模块,我们可以轻松地构建 Web 服务器、API 服务等。本文将深入探讨如何使用 http
模块来处理 HTTP 请求与响应,并给出相应的演示代码。
使用 http
模块创建一个简单的 HTTP 服务器非常容易。以下是一个基本的示例:
const http = require('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 running at http://localhost:${port}/`);
});
require('http')
:引入 Node.js 的 http
模块。http.createServer()
:创建一个 HTTP 服务器实例,它接受一个回调函数作为参数,该回调函数在每次收到请求时都会被调用。res.writeHead(200, { 'Content-Type': 'text/plain' })
:设置响应头,状态码为 200(表示成功),内容类型为纯文本。res.end('Hello, World!\n')
:发送响应内容并结束响应。server.listen(port, callback)
:让服务器监听指定的端口,并在服务器启动成功后执行回调函数。在实际应用中,我们通常需要根据不同的请求路径来返回不同的响应。以下是一个示例:
const http = require('http');
const server = http.createServer((req, res) => {
if (req.url === '/') {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Welcome to the home page!\n');
} else if (req.url === '/about') {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('This is the about page.\n');
} else {
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end('404 Not Found\n');
}
});
const port = 3000;
server.listen(port, () => {
console.log(`Server running at http://localhost:${port}/`);
});
req.url
:获取请求的 URL 路径。除了 GET 请求,我们还可以处理 POST 请求。以下是一个处理 POST 请求并接收表单数据的示例:
const http = require('http');
const querystring = require('querystring');
const server = http.createServer((req, res) => {
if (req.method === 'POST') {
let body = '';
req.on('data', (chunk) => {
body += chunk.toString();
});
req.on('end', () => {
const formData = querystring.parse(body);
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end(`Received data: ${JSON.stringify(formData)}\n`);
});
} else {
res.writeHead(405, { 'Content-Type': 'text/plain' });
res.end('Method Not Allowed\n');
}
});
const port = 3000;
server.listen(port, () => {
console.log(`Server running at http://localhost:${port}/`);
});
req.method
:获取请求的方法(如 GET、POST 等)。req.on('data', callback)
:监听 data
事件,当有数据传输时,将数据块追加到 body
变量中。req.on('end', callback)
:监听 end
事件,当数据传输结束时,使用 querystring.parse()
方法将表单数据解析为对象。功能 | 代码示例 | 解释 |
---|---|---|
创建 HTTP 服务器 | http.createServer((req, res) => { ... }) |
创建一个 HTTP 服务器实例,回调函数处理请求和响应 |
设置响应头 | res.writeHead(statusCode, headers) |
设置响应的状态码和头信息 |
发送响应内容 | res.end(content) |
发送响应内容并结束响应 |
获取请求路径 | req.url |
获取请求的 URL 路径 |
获取请求方法 | req.method |
获取请求的方法(如 GET、POST 等) |
处理 POST 数据 | req.on('data', callback) 和 req.on('end', callback) |
监听数据传输事件,接收并处理 POST 数据 |
Node.js 的 http
模块为我们提供了丰富的功能来处理 HTTP 请求与响应。通过本文的示例,你可以学习到如何创建简单的 HTTP 服务器、处理不同的请求路径以及接收 POST 请求数据。掌握这些知识后,你就可以开始构建自己的 Web 应用和 API 服务了。希望本文对你有所帮助!