res
是 Response 的缩写,表示 HTTP 响应对象。它是 Express 中非常重要的一个对象,用于向客户端(比如浏览器)发送响应。
1. res
对象的作用
res
对象的主要作用是:
- 设置响应头(Headers)。
- 发送响应数据(Body)。
- 设置状态码(Status Code)。
- 结束请求-响应周期。
通过 res
对象,我们可以控制服务器返回给客户端的内容和行为。
2. res
对象的常用方法
以下是 res
对象的一些常用方法:
(1) res.send()
- 作用:向客户端发送响应数据。
- 支持的数据类型:字符串、对象、数组、Buffer 等。
- 自动设置
Content-Type
响应头。
例子:
app.get('/', (req, res) => {
res.send('Hello, World!'); // 发送字符串
});
app.get('/json', (req, res) => {
res.send({ message: 'Hello, World!' }); // 发送 JSON 对象
});
(2) res.json()
- 作用:向客户端发送 JSON 数据。
- 自动设置
Content-Type
为application/json
。
例子:
app.get('/json', (req, res) => {
res.json({ message: 'Hello, World!' }); // 发送 JSON 数据
});
(3) res.status()
- 作用:设置 HTTP 状态码。
- 通常与
send()
或json()
一起使用。
例子:
app.get('/not-found', (req, res) => {
res.status(404).send('Page not found'); // 设置状态码为 404
});
app.get('/error', (req, res) => {
res.status(500).json({ error: 'Something went wrong' }); // 设置状态码为 500
});
(4) res.set()
或 res.header()
- 作用:设置响应头。
- 可以一次设置一个或多个响应头。
例子:
app.get('/', (req, res) => {
res.set('Content-Type', 'text/plain'); // 设置单个响应头
res.send('Hello, World!');
});
app.get('/multiple-headers', (req, res) => {
res.set({
'Content-Type': 'text/plain',
'X-Custom-Header': 'Hello'
}); // 设置多个响应头
res.send('Headers set!');
});
(5) res.type()
- 作用:设置
Content-Type
响应头。 - 可以传入 MIME 类型或文件扩展名。
例子:
app.get('/json', (req, res) => {
res.type('json'); // 设置 Content-Type 为 application/json
res.send({ message: 'Hello, World!' });
});
app.get('/html', (req, res) => {
res.type('html'); // 设置 Content-Type 为 text/html
res.send('<h1>Hello, World!</h1>');
});
(6) res.redirect()
- 作用:重定向客户端到另一个 URL。
- 可以设置状态码(默认是 302)。
例子:
app.get('/old-page', (req, res) => {
res.redirect('/new-page'); // 重定向到 /new-page
});
app.get('/temporary-redirect', (req, res) => {
res.redirect(301, '/new-page'); // 永久重定向
});
(7) res.sendFile()
- 作用:发送文件给客户端。
- 需要提供文件的绝对路径。
例子:
const path = require('path');
app.get('/file', (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'index.html')); // 发送 HTML 文件
});
(8) res.end()
- 作用:结束响应过程。
- 通常用于不需要发送数据的场景。
例子:
app.get('/end', (req, res) => {
res.status(204).end(); // 结束响应,不发送数据
});
(9) res.cookie()
- 作用:设置 Cookie。
- 可以设置 Cookie 的名称、值、过期时间等。
例子:
app.get('/set-cookie', (req, res) => {
res.cookie('username', 'John', { maxAge: 900000, httpOnly: true }); // 设置 Cookie
res.send('Cookie set!');
});
(10) res.clearCookie()
- 作用:清除指定的 Cookie。
例子:
app.get('/clear-cookie', (req, res) => {
res.clearCookie('username'); // 清除名为 username 的 Cookie
res.send('Cookie cleared!');
});
3. res
对象的常用属性
(1) res.statusCode
- 作用:获取或设置 HTTP 状态码。
例子:
app.get('/status', (req, res) => {
res.statusCode = 404; // 设置状态码为 404
res.send('Not Found');
});
(2) res.headersSent
- 作用:检查响应头是否已经发送。
- 返回布尔值(
true
或false
)。
例子:
app.get('/check-headers', (req, res) => {
if (res.headersSent) {
console.log('Headers already sent');
} else {
res.send('Headers not sent yet');
}
});
4. res
对象的使用场景
- 返回 HTML 页面:使用
res.send()
或res.sendFile()
。 - 返回 JSON 数据:使用
res.json()
。 - 设置响应头:使用
res.set()
或res.type()
。 - 重定向:使用
res.redirect()
。 - 设置 Cookie:使用
res.cookie()
。 - 结束请求:使用
res.end()
。
5. 完整示例
以下是一个完整的 Express 应用示例,展示了 res
对象的常见用法:
const express = require('express');
const app = express();
const path = require('path');
app.get('/', (req, res) => {
res.send('Hello, World!');
});
app.get('/json', (req, res) => {
res.json({ message: 'Hello, World!' });
});
app.get('/redirect', (req, res) => {
res.redirect('/new-page');
});
app.get('/new-page', (req, res) => {
res.send('This is the new page!');
});
app.get('/file', (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'index.html'));
});
app.get('/set-cookie', (req, res) => {
res.cookie('username', 'John', { maxAge: 900000 });
res.send('Cookie set!');
});
app.get('/clear-cookie', (req, res) => {
res.clearCookie('username');
res.send('Cookie cleared!');
});
app.listen(3000, () => {
console.log('Server is running on http://localhost:3000');
});
总结
res
对象是 Express 中用于向客户端发送响应的核心对象。- 它提供了丰富的方法,如
send()
、json()
、status()
、redirect()
等,用于处理不同的响应需求。 - 通过
res
对象,我们可以控制响应的状态码、响应头、响应体等内容。