10.介绍一些关于Express路由与响应方法

一、定义路由的方法

  1. app.get():定义一个处理 HTTP GET 请求的路由

  2. app.post:定义一个处理 HTTP POST 请求的路由

  3. 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

image.png

  • 打开客户端Postman,发送任意GET、POST、PUT的请求

image.png

二、?, *, +路由路径中的特殊字符

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

image.png

  • 打开客户端,发送请求http://127.0.0.1:3000/users/123

image.png

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/等路由

image.png

image.png

image.png

所以* 匹配了路径中的任意部分。

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等路由

image.png

image.png

image.png

在这个示例中,/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

image.png

  • 查看打印结果

image.png

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
最后更新时间' 2025/1/22 16:22:54