关于Express的一些路由与响应方法
【摘要】 Express.js 是一个流行的 Node.js Web 应用框架,提供了丰富的路由和响应方法,使得构建 Web 应用程序变得简单高效。本篇主要讲解是一些常用的路由和响应方法
一、定义路由的方法
-
app.get()
:定义一个处理 HTTP GET 请求的路由 -
app.post
:定义一个处理 HTTP POST 请求的路由 -
app.all()
:处理所有 HTTP 请求方法(如 GET、POST、PUT 等)的路由
- app.js
const express = require("express");
const app = express();
app.all('/test', (req, res) => {
res.send('all in')
})
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server is running at http://localhost:${PORT}`);
});
- 运行项目
npm run dev
- 打开客户端
Postman
,发送任意GET、POST、PUT
的请求
二、?, *, +
路由路径中的特殊字符
1、?
(可选字符)
表示前面的一个字符或路径段是可选的。
app.js
const express = require("express");
const app = express();
// `?`(可选字符)
app.get('/users/:id?', (req, res) => {
const userId = req.params.id;
if (userId) {
res.send(`userid: ${userId}`);
} else {
res.send('未提供用户ID');
}
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server is running at http://localhost:${PORT}`);
});
- 运行项目
npm run dev
/users/
和/users/123
都会匹配该路由。如果提供了 id,则返回用户 ID;如果没有提供 id,则返回提示信息。
- 打开客户端,发送请求
http://127.0.0.1:3000/users
- 打开客户端,发送请求
http://127.0.0.1:3000/users/123
2、*(任意字符)
表示匹配任意数量的任意字符
app.js
const express = require("express");
const app = express();
// `*` 匹配任意数量的任意字符。
app.get('/files/*', (req, res) => {
res.send('File path: ' + req.path);
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server is running at http://localhost:${PORT}`);
});
- 运行项目
npm run dev
- 打开客户端匹配
/files/abc, /files/123/456, /files/
等路由
所以
*
匹配了路径中的任意部分。
3、+(一个或多个字符)
表示前面的字符或路径段必须出现一次或多次。
app.js
const express = require("express");
const app = express();
// `+`(一个或多个字符)
app.get('/users/+:id', (req, res) => {
res.send(`User ID: ${req.params.id}`);
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server is running at http://localhost:${PORT}`);
});
- 运行项目
npm run dev
- 打开客户端匹配
/users/123, /users/,/users///123
等路由
在这个示例中,
/users/123
会匹配该路由,但/users/
不会匹配,因为 + 要求 id 至少出现一次。
三、Express路由响应方法
1、req.params
获取路由参数
2、req.url
获取请求的 URL 路径部分,不包括查询字符串
如果请求的 URL 是 /users/123?name=John,那么 req.url 的值将是 ‘/users/123’,不包括查询字符串部分 ?name=John.
3、req.method
是一个属性,用于获取当前请求的 HTTP 方法,常见的方法包括GET、POST、PUT、DELETE
等
常见 HTTP 方法:
-
GET:用于请求资源,通常用于获取数据
-
POST:用于提交数据,通常用于创建新资源
-
PUT:用于更新资源,通常用于替换资源的全部内容
-
DELETE:用于删除资源
-
PATCH:用于更新资源的部分内容
-
app.js
demo
const express = require("express");
const app = express();
app.get('/users/:id', (req, res) => {
console.log(req.params);
res.send(`User ID: ${req.params.id}`);
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server is running at http://localhost:${PORT}`);
});
- 运行项目
npm run dev
- 打开客户端,发送
http://127.0.0.1:3000/users/123
- 查看打印结果
5、res.send()
通用方法,可以发送多种类型的数据.
res.send('Hello, world!'); // 发送字符串
res.send({ name: 'John', age: 30 }); // 发送对象
res.send([1, 2, 3]); // 发送数组
6、res.download()
用于发送文件作为下载响应,专门用于文件下载
res.download('/path/to/file.zip'); // 使用文件的原始名称
res.download('/path/to/file.zip', 'downloaded-file.zip'); // 使用自定义文件名
7、res.end()
用于结束响应过程,不发送任何内容
res.end(); // 结束响应,不发送内容
res.end('Hello'); // 结束响应并发送字符串
8、res.json()
用于发送 JSON 格式的响应,专门用于发送 JSON 格式的响应,自动设置 Content-Type.
res.json({ name: 'John', age: 30 }); // 发送 JSON 对象
res.json([1, 2, 3]); // 发送 JSON 数组
9、res.redirect()
用于将客户端重定向到另一个 URL
res.redirect('/home'); // 临时重定向到 /home 默认为 302(临时重定向)
res.redirect(301, '/new-url'); // 永久重定向到 /new-url
10、res.render()
用于渲染视图模板,并将渲染后的 HTML 发送给客户端
// 假设有一个名为 'profile' 的视图文件
res.render('profile', { name: 'John', age: 30 });
11、res.sendStatus()
用于发送一个 HTTP 状态码作为响应.
res.sendStatus(200); // 发送 200 OK
res.sendStatus(404); // 发送 404 Not Found
【声明】本内容来自华为云开发者社区博主,不代表华为云及华为云开发者社区的观点和立场。转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息,否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
作者其他文章
评论(0)