Response 对象(简称 res)
res对象表示 Express 应用程序在收到 HTTP 请求时发送的 HTTP 响应。
在本文档中,按照惯例,该对象始终被称为res(而 HTTP 请求为req),但其实际名称由你正在使用的回调函数的参数决定。
res主要用于给客户端响应东西的,所以属性比较少,就不做介绍了。
Response 方法
send:发送数据; 参数可以是Buffer、String、Boolean、Array。json:发送 JSON 数据。sendFile:发送静态文件。sendStatus:发送状态码。status:发送状态码,并在通过 send 或 sendFile 返回内容set:发送响应头信息herder:发送响应头信息, 与 set 一致get:获取设置的响应头信息redirect:重定向render:渲染模板cookie:设置cookieclearCookie:删除cookie
send 示例
app.get('/', (req, res) => {
// res.send('纯文本');
// res.send('<h1>HTML标签</h1>');
// res.send({name: 对象});
res.send('send 不能重复出现,send返回最终结果');
});
json 示例
app.get('/', (req, res) => {
res.json({name: JSON对象});
});
sendFile 示例
import express from 'express';
import { fileURLToPath } from 'url';
import { dirname, join } from 'path';
// 获取当前模块的文件路径
const __filename = fileURLToPath(import.meta.url);
// 获取当前模块所在的目录路径
const __dirname = dirname(__filename);
const app = express();
const port = 3000;
app.get('/', (req, res) => {
// 发送 public 目录下的 index.html 文件
res.sendFile(join(__dirname, '/public/html/index.html'));
});
app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});
- import.meta.url 是 ES Modules 提供的一个元数据属性,它表示当前模块文件的 URL。借助 url 模块可以将其转换为文件系统路径。
sendStatus / status 示例
import express from 'express';
import { fileURLToPath } from 'url';
import { dirname, join } from 'path';
const app = express();
const port = 3000;
app.get('/', (req, res) => {
// 发送 sendStatus
res.sendStatus(404); // 发送状态码,会返回 Not Found 不友好!
// 发送 status
res.status(404).send('没有找到该页面'); // 发送状态吗,并使用 send 发送文本信息
});
app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});
set / herder 示例
app.get('/', (req, res) => {
res.status(200).set('Content-Type', 'text/plain').sendFile(join(__dirname, '/public/html/index.html'));
});
// set参数设置多个用对象的写法;
// 用 sendFile 示例,并添加响应头 'Content-Type', 'text/plain'
// 浏览器则识别为文本展示
// <!DOCTYPE html>
// <html lang="en">
// <head>
// <meta charset="UTF-8">
// <title>首页</title>
// <link rel="stylesheet" href="/pubilc/css/global.css">
// </head>
// <body>
// <h1>欢迎欢迎,热烈欢迎</h1>
// </body>
// </html>
get 示例
app.get('/', (req, res) => {
res.status(200).set('Content-Type', 'text/plain')
console.log('Content-Type', res.get('Content-Type')); // Content-Type text/plain; charset=utf-8
res.sendFile(join(__dirname, '/public/html/index.html'));
});
redirect 示例
app.get('/', (req, res) => {
// 比如 这里是判断当前用户未登录
if (true) {
// 执行重定向跳转至登录页面
res.redirect('/login');
}
res.sendFile(join(__dirname, '/public/html/index.html'));
});