Express.js 是一个流行的 Node.js Web 应用框架,提供了丰富的路由和响应方法,使得构建 Web 应用程序变得简单高效。本篇主要讲解是一些常用的路由和响应方法
app.get()
:定义一个处理 HTTP GET 请求的路由app.post
:定义一个处理 HTTP POST 请求的路由app.all()
:处理所有 HTTP 请求方法(如 GET、POST、PUT 等)的路由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
的请求?, *, +
路由路径中的特殊字符?
(可选字符)表示前面的一个字符或路径段是可选的。
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}`);
});
/users/
和/users/123
都会匹配该路由。如果提供了 id,则返回用户 ID;如果没有提供 id,则返回提示信息。
http://127.0.0.1:3000/users
http://127.0.0.1:3000/users/123
表示匹配任意数量的任意字符
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/
等路由所以
*
匹配了路径中的任意部分。
表示前面的字符或路径段必须出现一次或多次。
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 至少出现一次。
req.params
获取路由参数req.url
获取请求的 URL 路径部分,不包括查询字符串如果请求的 URL 是 /users/123?name=John,那么 req.url 的值将是 '/users/123',不包括查询字符串部分 ?name=John.
req.method
是一个属性,用于获取当前请求的 HTTP 方法,常见的方法包括GET、POST、PUT、DELETE
等常见 HTTP 方法:
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
res.send()
通用方法,可以发送多种类型的数据.res.send('Hello, world!'); // 发送字符串
res.send({ name: 'John', age: 30 }); // 发送对象
res.send([1, 2, 3]); // 发送数组
res.download()
用于发送文件作为下载响应,专门用于文件下载res.download('/path/to/file.zip'); // 使用文件的原始名称
res.download('/path/to/file.zip', 'downloaded-file.zip'); // 使用自定义文件名
res.end()
用于结束响应过程,不发送任何内容res.end(); // 结束响应,不发送内容
res.end('Hello'); // 结束响应并发送字符串
res.json()
用于发送 JSON 格式的响应,专门用于发送 JSON 格式的响应,自动设置 Content-Type.res.json({ name: 'John', age: 30 }); // 发送 JSON 对象
res.json([1, 2, 3]); // 发送 JSON 数组
res.redirect()
用于将客户端重定向到另一个 URLres.redirect('/home'); // 临时重定向到 /home 默认为 302(临时重定向)
res.redirect(301, '/new-url'); // 永久重定向到 /new-url
res.render()
用于渲染视图模板,并将渲染后的 HTML 发送给客户端// 假设有一个名为 'profile' 的视图文件
res.render('profile', { name: 'John', age: 30 });
res.sendStatus()
用于发送一个 HTTP 状态码作为响应.res.sendStatus(200); // 发送 200 OK
res.sendStatus(404); // 发送 404 Not Found
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。