HTTP 模块是 Node.js 核心模块之一,提供了创建 HTTP 服务器和客户端的功能。以下是 HTTP 模块的一些主要内容和使用方法的详细讲解。
创建 HTTP 服务器
-
http.createServer([requestListener])
: 创建一个 HTTP 服务器实例。requestListener
是一个处理请求的回调函数,每当有请求进来时就会被调用。const http = require('http'); const server = http.createServer((req, res) => { res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('Hello, World!'); }); server.listen(3000, '127.0.0.1', () => { console.log('Server listening on port 3000'); });
处理 HTTP 请求和响应
-
request
对象: 表示客户端的请求,提供了关于请求的信息。const http = require('http'); const server = http.createServer((req, res) => { console.log('Request Method:', req.method); console.log('Request URL:', req.url); res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('Hello, World!'); }); server.listen(3000, '127.0.0.1', () => { console.log('Server listening on port 3000'); });
-
response
对象: 表示服务器对客户端请求的响应,通过该对象可以发送响应数据。const http = require('http'); const server = http.createServer((req, res) => { res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('Hello, World!'); }); server.listen(3000, '127.0.0.1', () => { console.log('Server listening on port 3000'); });
处理 POST 请求
-
处理 POST 请求: 监听
data
和end
事件来获取 POST 请求的数据。const http = require('http'); const server = http.createServer((req, res) => { if (req.method === 'POST') { let data = ''; req.on('data', (chunk) => { data += chunk; }); req.on('end', () => { console.log('Received data:', data); res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('Data received successfully.'); }); } else { res.writeHead(404, {'Content-Type': 'text/plain'}); res.end('Not Found'); } }); server.listen(3000, '127.0.0.1', () => { console.log('Server listening on port 3000'); });
创建 HTTP 客户端
-
http.request(options[, callback])
: 创建一个 HTTP 客户端实例。options
定义了请求的参数,callback
是一个回调函数,在响应可用时被调用。const http = require('http'); const options = { hostname: 'www.example.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('Response:', data); }); }); req.end();
完整的 HTTP 客户端和服务器
-
完整的 HTTP 客户端和服务器: 将上述的创建服务器和客户端的功能结合使用。
const http = require('http'); // 创建 HTTP 服务器 const server = http.createServer((req, res) => { res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('Hello, World!'); }); server.listen(3000, '127.0.0.1', () => { console.log('Server listening on port 3000'); }); // 创建 HTTP 客户端 const clientOptions = { hostname: '127.0.0.1', port: 3000, path: '/', method: 'GET', }; const clientReq = http.request(clientOptions, (res) => { let data = ''; res.on('data', (chunk) => { data += chunk; }); res.on('end', () => { console.log('Client Response:', data); }); }); clientReq.end();