Node.js中的 http 模块详解
http 模块是 Node.js 中的核心模块之一,专门用于构建基于 HTTP 的网络应用程序。它允许创建 HTTP 服务器和客户端,处理网络请求和响应。
1. 核心 API 详解
1.1. http.createServer([options][, requestListener])
用于创建 HTTP 服务器的核心方法,返回一个 http.Server 实例,可监听指定端口并处理请求。
options(可选):用于提供服务器配置,允许指定 HTTP/1.1、HTTP/2 等协议。
requestListener(可选):一个回调函数,在每次接收到客户端请求时调用。
const http = require('http');
const server = http.createServer((req, res) => {res.statusCode = 200;res.setHeader('Content-Type', 'text/plain');res.end('Hello, world!\n');
});
server.listen(3000, '127.0.0.1', () => {console.log('Server running at http://127.0.0.1:3000/');
});
req:包含请求的详细信息,比如 URL、HTTP 方法、请求头等。
res:用于响应客户端请求,可以设置状态码、响应头以及响应体。
1.2. request and response Objects
1. http.IncomingMessage
表示服务器接收到的请求,是一个可读流,用于获取请求体和元数据。
常用属性:
req.method:请求的方法。
req.url:请求的路径和查询参数。
req.headers:请求的头部信息。
2. http.ServerResponse
表示服务器对客户端的响应,是一个可写流,用于发送响应数据。
常用方法:
res.writeHead(statusCode[, headers]):设置状态码和头部信息。
res.end([data[, encoding]][, callback]):结束响应并可以发送数据。
1.3. http.request(options[, callback])
用于创建 HTTP 客户端请求。
const options = {hostname: 'www.google.com',port: 80,path: '/',method: 'GET',
};
const req = http.request(options, (res) => {let data = '';res.on('data', (chunk) => {data += chunk;});res.on('end', () => {console.log(data);});
});
req.on('error', (e) => {console.error(`Problem with request: ${e.message}`);
});
req.end();
options:用于配置请求的目标、方法、头信息等。
callback:处理响应的回调函数。
1.4. http.get(options[, callback])
这是一个简化版的 http.request,专门用于 GET 请求,自动调用 req.end(),不需要显式调用。
http.get('http://www.google.com', (res) => {res.on('data', (chunk) => {console.log(`Data chunk: ${chunk}`);});res.on('end', () => {console.log('No more data.');});
});
2. 实战项目:简单的 HTTP 服务器与客户端
创建一个简单的 HTTP 服务器,它可以响应客户端的 GET 和 POST 请求。同时,通过客户端请求获取服务器上的数据。
2.1. 创建 HTTP 服务器
在服务器端,接受 GET 和 POST 请求,并返回不同的响应。
const http = require('http');
const server = http.createServer((req, res) => {if (req.method === 'GET' && req.url === '/') {res.writeHead(200, { 'Content-Type': 'application/json' });res.end(JSON.stringify({ message: 'Welcome to the GET request!' }));} else if (req.method === 'POST' && req.url === '/submit') {let body = '';req.on('data', (chunk) => {body += chunk.toString();});req.on('end', () => {res.writeHead(200, { 'Content-Type': 'application/json' });res.end(JSON.stringify({ message: 'Data received!', data: body }));});} else {res.writeHead(404, { 'Content-Type': 'text/plain' });res.end('404 Not Found');}
});
server.listen(3000, () => {console.log('Server listening on port 3000');
});
2.2. 创建 HTTP 客户端
客户端将发送 GET 和 POST 请求来与服务器进行交互。
const http = require('http');
// Send GET request
http.get('http://localhost:3000', (res) => {let data = '';res.on('data', (chunk) => {data += chunk;});res.on('end', () => {console.log('GET Response:', data);});
});
// Send POST request
const postData = JSON.stringify({ name: 'John', age: 30 });
const options = {hostname: 'localhost',port: 3000,path: '/submit',method: 'POST',headers: {'Content-Type': 'application/json','Content-Length': postData.length,},
};
const req = http.request(options, (res) => {let data = '';res.on('data', (chunk) => {data += chunk;});res.on('end', () => {console.log('POST Response:', data);});
});
req.write(postData);
req.end();
通过 http 模块直接实现 WebSocket (WS) 协议是一项深入底层协议的工作。WebSocket 是基于 TCP 的协议,在其通信过程中,依赖于 HTTP 协议的握手机制,但通信方式和 HTTP 不同,它允许建立一个长期的、双向的连接。为了实现 WebSocket 服务器,需要结合对 HTTP 和 WebSocket 握手机制、数据帧协议以及 TCP/IP 模型的理解。