内置模块 http
约 1605 字大约 5 分钟
2025-03-15
一、模块概述
1、模块介绍
http 模块是 Node.js 内置模块之一,提供了基础的 HTTP 功能,包括处理 HTTP 请求和响应。开发者可以使用 http 模块创建服务器,监听指定端口并处理来自客户端的 HTTP 请求。它支持 HTTP/1.1 协议,并能够处理常见的 HTTP 请求方法,如 GET、POST、PUT、DELETE 等。
2、模块的核心功能
http 模块的核心功能可以概括为以下几项:
- 创建 HTTP 服务器: 监听指定端口,处理客户端请求。
- 处理 HTTP 请求: 解析 HTTP 请求头、请求方法、URL 及其他相关信息。
- 生成 HTTP 响应: 构建和发送 HTTP 响应,包括状态码、响应头和响应主体。
- 创建 HTTP 客户端: 发起 HTTP 请求,与其他服务器通信。
3、主要应用场景
- HTTP 服务器:提供
RESTful API 服务
、开发者可以使用http
模块创建简单的RESTful API
服务,提供数据访问和操作接口。 - 代理服务器:通过
http
模块,可以创建代理服务器,转发客户端请求到其他服务器,并将响应返回给客户端。 - WebSocket 服务器:虽然
http
模块本身不支持WebSocket
,但可以通过结合其他模块(如ws
或socket.io
)来实现 WebSocket 通信,提供实时数据交互功能 。
二、基本用途
1、创建 HTTP 服务器
使用 http
模块创建一个简单的 HTTP 服务器 (服务端),提供基本的 Restful API
服务。我们需要调用 http.createServer
方法,并传入一个回调函数。该回调函数会在每次接收到请求时被调用,处理请求并发送响应给客户端。
const http = require("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("Server running at http://localhost:3000/");
});
2、根据 URL 和方法处理
在服务器中,req
对象包含了客户端请求的所有信息。通过 req.url
可以获取请求的 URL,通过 req.method
可以获取请求的方法(如 GET、POST)。
下面是一个根据不同 URL 返回不同响应的例子:
const http = require("http");
const server = http.createServer((req, res) => {
if (req.url === "/" && req.method === "GET") {
res.writeHead(200, { "Content-Type": "text/html" });
res.end("<h1>Welcome to the homepage!</h1>");
} else if (req.url === "/about" && req.method === "GET") {
res.writeHead(200, { "Content-Type": "text/html" });
res.end("<h1>About us page</h1>");
} else {
res.writeHead(404, { "Content-Type": "text/html" });
res.end("<h1>404 Not Found</h1>");
}
});
server.listen(3000, () => {
console.log("Server running at http://localhost:3000/");
});
在这个例子中:
- 根据
req.url
和req.method
区分不同的请求。 - 对
/
和/about
两个路径进行处理,并返回不同的 HTML 响应。 - 对未匹配的路径返回 404 页面。
3、处理 POST 请求
在处理 POST 请求时,数据通常是通过 请求主体(body
) 发送的。Node.js 的 http
模块允许你监听请求对象的 data
和 end
事件来处理 POST 请求中的数据。
以下代码展示了如何处理 POST 请求中的数据:
const http = require("http");
const server = http.createServer((req, res) => {
if (req.method === "POST" && req.url === "/submit") {
let body = "";
// 监听 data 事件,接收数据块
req.on("data", (chunk) => {
body += chunk.toString();
});
// 监听 end 事件,处理接收到的完整数据
req.on("end", () => {
res.writeHead(200, { "Content-Type": "text/plain" });
res.end(`Received data: ${body}`);
});
} else {
res.writeHead(404, { "Content-Type": "text/plain" });
res.end("404 Not Found");
}
});
server.listen(3000, () => {
console.log("Server running at http://localhost:3000/");
});
在这个例子中:
- 通过
req.on('data')
事件监听传输中的数据块,并将其累加到body
变量中。 - 当所有数据接收完毕时,触发
req.on('end')
事件,处理完整的请求数据。 - 最后将接收到的数据返回给客户端。
三、其他主要功能
1、设置响应头和状态码
在 HTTP 响应中,状态码和头信息至关重要。通过 res.writeHead 方法可以设置状态码和头信息。例如,200 表示请求成功,404 表示资源未找到。
res.writeHead(200, { "Content-Type": "text/html" });
常见的 HTTP 状态码包括:
- 200:请求成功。
- 304:请求成功,但是访问的是浏览器缓存。
- 401:未授权。
- 404:资源未找到。
- 500:服务器内部错误。
- 502:服务器内部错误。
2、处理 JSON 数据
Node.js 的 http 模块不仅支持文本数据,还可以处理 JSON
格式的数据。以下代码展示了如何返回 JSON 响应:
const http = require("http");
const server = http.createServer((req, res) => {
const jsonResponse = {
message: "Hello, World!",
status: "success",
};
res.writeHead(200, { "Content-Type": "application/json" });
res.end(JSON.stringify(jsonResponse));
});
server.listen(3000, () => {
console.log("Server running at http://localhost:3000/");
});
在这个例子中,res.writeHead
设置了 Content-Type
为 application/json
,并通过 JSON.stringify
将 JavaScript 对象转换为 JSON 字符串。
3、创建 HTTP 客户端
除了创建服务器,http
模块还可以用来发起 HTTP 请求,充当客户端。
以下是一个
http.get
请求的示例:const http = require("http"); http.get("http://api.example.com/data", (res) => { let data = ""; // 监听数据接收 res.on("data", (chunk) => { data += chunk; }); // 请求结束后处理完整响应 res.on("end", () => { console.log(`Received data: ${data}`); }); }).on("error", (err) => { console.error(`Error: ${err.message}`); });
以下是一个
http.request
请求的示例:const postData = JSON.stringify({ msg: "Hello World!", }); const options = { hostname: "www.google.com", port: 80, path: "/upload", method: "POST", headers: { "Content-Type": "application/json", "Content-Length": Buffer.byteLength(postData), }, }; const req = http.request(options, (res) => { console.log(`STATUS: ${res.statusCode}`); console.log(`HEADERS: ${JSON.stringify(res.headers)}`); res.setEncoding("utf8"); res.on("data", (chunk) => { console.log(`BODY: ${chunk}`); }); res.on("end", () => { console.log("No more data in response."); }); }); req.on("error", (e) => { console.error(`problem with request: ${e.message}`); }); // 将请求数据吸入req req.write(postData); req.end();
4、处理返回值
write 和 end 的两种使用情况:
//1. write 和 end 的结合使用 响应体相对分散
response.write('xx');
response.write('xx');
response.write('xx');
response.end(); //每一个请求,在处理的时候必须要执行 end 方法的
//2. 单独使用 end 方法 响应体相对集中
response.end('xxx');
四、实际应用场景
1、简单的 RESTful API 服务
利用 http
模块,你可以创建一个简单的 RESTful API,处理 CRUD 操作,返回 JSON 数据。例如,响应客户端的 GET、POST、PUT、DELETE 请求并返回相应的资源状态。
2、代理服务器
你可以使用 http
模块创建一个代理服务器,转发客户端请求至其他服务器,再将其他服务器的响应返回给客户端。
const http = require("http");
const https = require("https");
const server = http.createServer((req, res) => {
const proxy = https.request("https://example.com", (proxyRes) => {
proxyRes.pipe(res);
});
req.pipe(proxy);
});
server.listen(3000, () => {
console.log("Proxy server running at http://localhost:3000/");
});
3、WebSocket 服务器
虽然 http
模块本身不支持 WebSocket,但可以作为 WebSocket 服务器的基础,通过 ws
等第三方库实现实时通信。
更新日志
e7112
-1于