在 Express 中获取请求正文
Express 不会自动为您解析 HTTP 请求体,但它确实有一个 官方支持的中间件包来解析 HTTP 请求体 。 从 v4.16.0 开始,Express 带有一个 内置的 JSON 请求正文解析中间件 ,对于大多数 JavaScript 应用程序来说已经足够好了。
JSON 请求正文
Express 内置 express.json()
函数 返回一个 Express 中间件函数 ,该函数将 JSON HTTP 请求正文解析为 JavaScript 对象 。 这 json()
中间件添加了一个 body
的属性 快速请求 req
。要访问已解析的请求正文,请使用 req.body
如下所示。
const express = require('express');
const app = express();
// Parse JSON bodies for this app. Make sure you put
// `app.use(express.json())` **before** your route handlers!
app.use(express.json());
app.post('*', (req, res) => {
req.body; // JavaScript object containing the parse JSON
res.json(req.body);
});
const server = await app.listen(3000);
// Demo showing the server in action
const axios = require('axios');
const res = await axios.post('http://localhost:3000/', {
answer: 42
});
res.data; // `{ answer: 42 }`
常见问题
如果 JSON 正文格式错误,Express 将出错并显示 HTTP 400。此错误还会触发 错误处理中间件 。
const express = require('express');
const app = express();
app.use(express.json());
app.post('*', (req, res) => {
res.json(req.body);
});
// Add error handling middleware that Express will call
// in the event of malformed JSON.
app.use(function(err, req, res, next) {
// 'SyntaxError: Unexpected token n in JSON at position 0'
err.message;
next(err);
});
const server = await app.listen(3000);
// Demonstrate the server in action
const axios = require('axios');
const headers = { 'Content-Type': 'application/json' };
const err = await axios.
post('http://localhost:3000/', 'not json', { headers }).
then(() => null, err => err);
// Express will send an HTTP 400 by default if JSON middleware
// failed to parse.
err.response.status; // 400
err.message; // 'Request failed with status code 400'
需要注意的是,默认情况下, json()
中间件忽略任何请求 Content-Type
标头不是 Express 识别为 JSON 的东西。 如果 express.json()
默默无视您的请求,请确保您检查 Content-Type
标题。
const express = require('express');
const app = express();
app.use(express.json());
app.post('*', (req, res) => {
// undefined, body parser ignored this request
// because of the content-type header
req.body;
res.json(req.body);
});
const server = await app.listen(3000);
// Demo of making a request the JSON body parser ignores.
const axios = require('axios');
const headers = { 'Content-Type': 'text/plain' };
const res = await axios.
post('http://localhost:3000/', 'not json', { headers });
res.data; // Empty object `{}`
URL 编码的表单正文解析器
Express 有一个官方支持的模块 body-parser ,它包括一个 用于 URL 编码请求体 提交的那些 HTML 表单 。
const express = require('express');
const app = express();
app.use(require('body-parser').urlencoded({ extended: false }));
app.post('*', (req, res) => {
req.body; // { answer: 42 }
res.json(req.body);
});
const server = await app.listen(3000);
// Demo of making a request with a URL-encoded body.
const axios = require('axios');
const headers = {
'Content-Type': 'application/x-www-form-urlencoded'
};
const res = await axios.
post('http://localhost:3000/', 'answer=42', { headers });
res.data; // { answer: 42 }
接收文件
Express 和 body-parser 都不支持开箱即用的文件上传。
但是,您可以使用 npm 上的 强大 模块来处理文件上传。 在这个教程中了解如何操作 使用 Express 上传文件 。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

上一篇: Express 中的路由参数
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论