express模块响应对象

resResponse 的缩写,表示 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-Typeapplication/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
  • 作用:检查响应头是否已经发送。
  • 返回布尔值(truefalse)。

例子

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 对象,我们可以控制响应的状态码、响应头、响应体等内容。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

鸭梨山大哎

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值