express.static()
用于托管静态文件(如 HTML、CSS、JavaScript、图片等)。它可以将指定目录中的文件提供给客户端。
使用:
const path = require("path");
const staticRoot = path.resolve(__dirname, "../public");
/**
* 下面这段代码的作用:
* 当请求时,会根据请求路径,从指定的目录中寻找是否存在该文件,如果存在,直接响应文件内容,而不再移交给后续的中间件
* 如果不存在文件,直接移交给后续的中间件处理
*默认情况下,如果映射的结果是一个目录,会自动使用index.html存不存在
*/
app.use(express.static(staticRoot){
//配置文件
index:"default.html"
});
express.json()
用于解析传入的请求体(body)中的 JSON 数据。它通常用于处理 Content-Type: application/json 的请求。
app.use(express.json());
客户端发送 JSON 数据:
{
"name": "John",
"age": 30
}
服务器端代码:
app.post('/user', (req, res) => {
console.log(req.body); // { name: "John", age: 30 }
res.send('Data received');
});
express.urlencoded()
用于解析传入的请求体中的 URL 编码数据(通常来自 HTML 表单提交)。它通常用于处理 Content-Type: application/x-www-form-urlencoded 的请求。
const express = require('express');
const app = express();
// 解析 URL 编码的请求体
app.use(express.urlencoded({ extended: true }));
注意:必须配置extended,如果不配置会报错
-
extended:
true: 使用qs库解析复杂对象。false: 使用querystring库解析简单对象。
-
手写
express.urlencoded()
exports.urlencoded = (options = {}) => {
options.type = options.type || "application/x-www-form-urlencoded";
return (req, res, next) => {
if (req.headers["content-type"] == options.type) {
// 自行解析消息体
let result = "";
req.on("data", (chunk) => {
result += chunk.toString("utf-8");
});
req.on("end", () => {
const query = qs.parse(result);
req.body = query;
next();
});
} else {
next();
}
};
};
总结
| 方法 | 用途 | 常见场景 |
|---|---|---|
express.static | 托管静态文件(如 HTML、CSS、JS) | 提供前端资源文件 |
express.json() | 解析 JSON 格式的请求体 | 处理 API 请求(如 POST 数据) |
express.urlencoded() | 解析 URL 编码的请求体(表单数据) | 处理 HTML 表单提交 |