在 Express 中获取请求正文

发布于 2022-08-20 00:56:58 字数 4455 浏览 203 评论 0

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据

关于作者

文章
评论
27 人气
更多

推荐作者

櫻之舞

文章 0 评论 0

弥枳

文章 0 评论 0

m2429

文章 0 评论 0

野却迷人

文章 0 评论 0

我怀念的。

文章 0 评论 0

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文