http 模块详解

Node.js 是一个基于 Chrome V8 引擎的 JavaScript 运行环境,适合构建高效、可扩展的网络应用。在 Node.js 中,http 模块是核心模块之一,允许开发者创建 HTTP 服务器与客户端,处理请求和响应。本文将详细介绍 http 模块的核心功能和应用场景,帮助你掌握如何使用它来构建服务器端应用。

http 模块概述

模块介绍

http 模块是 Node.js 内置模块之一,提供了基础的 HTTP 功能,包括处理 HTTP 请求和响应。开发者可以使用 http 模块创建服务器,监听指定端口并处理来自客户端的 HTTP 请求。它支持 HTTP/1.1 协议,并能够处理常见的 HTTP 请求方法,如 GET、POST、PUT、DELETE 等。

模块的核心功能

http 模块的核心功能可以概括为以下几项:

  • 创建 HTTP 服务器:监听指定端口,处理客户端请求。
  • 处理 HTTP 请求:解析 HTTP 请求头、请求方法、URL 及其他相关信息。
  • 生成 HTTP 响应:构建和发送 HTTP 响应,包括状态码、响应头和响应主体。
  • 创建 HTTP 客户端:发起 HTTP 请求,与其他服务器通信。

http 模块的基本用法

创建简单的 HTTP 服务器

要使用 http 模块创建一个简单的 HTTP 服务器,你需要调用 http.createServer 方法,并传入一个回调函数。该回调函数会在每次接收到请求时被调用,处理请求并发送响应。

以下代码展示了如何创建一个简单的 HTTP 服务器:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
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/');
});

在上述代码中:

  • http.createServer 创建了一个新的 HTTP 服务器。
  • 传入的回调函数接收两个参数 req(请求对象)和 res(响应对象)。
  • 通过 res.writeHead 设置响应的状态码和头信息,并通过 res.end 发送响应数据。
  • 服务器通过 server.listen 监听端口 3000,并在启动成功后输出日志。

处理 URL 和请求方法

在服务器中,req 对象包含了客户端请求的所有信息。通过 req.url 可以获取请求的 URL,通过 req.method 可以获取请求的方法(如 GET、POST)。

下面是一个根据不同 URL 返回不同响应的例子:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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.urlreq.method 区分不同的请求。
  • //about 两个路径进行处理,并返回不同的 HTML 响应。
  • 对未匹配的路径返回 404 页面。

处理 POST 请求

在处理 POST 请求时,数据通常是通过请求主体(body)发送的。Node.js 的 http 模块允许你监听请求对象的 dataend 事件来处理 POST 请求中的数据。

以下代码展示了如何处理 POST 请求中的数据:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
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') 事件,处理完整的请求数据。
  • 最后将接收到的数据返回给客户端。

http 模块的高级功能

设置响应头和状态码

在 HTTP 响应中,状态码和头信息至关重要。通过 res.writeHead 方法可以设置状态码和头信息。例如,200 表示请求成功,404 表示资源未找到。

1
res.writeHead(200, { 'Content-Type': 'text/html' });

常见的 HTTP 状态码包括:

  • 200:请求成功。
  • 404:资源未找到。
  • 500:服务器内部错误。

处理 JSON 数据

Node.js 的 http 模块不仅支持文本数据,还可以处理 JSON 格式的数据。以下代码展示了如何返回 JSON 响应:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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-Typeapplication/json,并通过 JSON.stringify 将 JavaScript 对象转换为 JSON 字符串。

创建 HTTP 客户端

除了创建服务器,http 模块还可以用来发起 HTTP 请求,充当客户端。以下是一个发起 GET 请求的示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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.get 用于发起 GET 请求,返回的数据通过监听 dataend 事件处理。

实际应用场景

简单的 RESTful API 服务

利用 http 模块,你可以创建一个简单的 RESTful API,处理 CRUD 操作,返回 JSON 数据。例如,响应客户端的 GET、POST、PUT、DELETE 请求并返回相应的资源状态。

代理服务器

你可以使用 http 模块创建一个代理服务器,转发客户端请求至其他服务器,再将其他服务器的响应返回给客户端。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
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/');
});

WebSocket 服务器

虽然 http 模块本身不支持 WebSocket,但可以作为 WebSocket 服务器的基础,通过 ws 等第三方库实现实时通信。

总结

Node.js 的 http 模块为开发者提供了强大的工具来构建高效的 HTTP 服务器与客户端。通过对 http 模块的深入理解,你可以轻松创建 RESTful API、代理服务器或其他网络应用。在使用 http 模块时,掌握请求与响应的处理、头信息的设置以及数据的传输方式,是开发稳定高效应用的基础。