且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

获取 POST 请求中的空正文

更新时间:2022-11-07 18:47:31

问题是

mode: 'no-cors'

来自文档...

防止方法成为除 HEAD、GET 或 POST 之外的任何东西,并且防止标头成为除 简单标题

Prevents the method from being anything other than HEAD, GET or POST, and the headers from being anything other than simple headers

简单内容类型标题限制允许

  • 文本/纯文本,
  • application/x-www-form-urlencoded,以及
  • multipart/form-data

这会使您精心设计的 Content-Type: application/json 标头变为 content-type: text/plain(至少在通过 Chrome 测试时).

This causes your nicely crafted Content-Type: application/json header to become content-type: text/plain (at least when tested through Chrome).

由于您的 Express 服务器需要 JSON,它不会解析此请求.

Since your Express server is expecting JSON, it won't parse this request.

我建议省略 mode 配置.这将使用默认的 "cors" 选项.

I recommend omitting the mode config. This uses the default "cors" option instead.

由于您的请求不是 简单,您可能需要添加一些 CORS 中间件您的 Express 服务器.

Since your request is not simple, you'll probably want to add some CORS middleware to your Express server.

另一个(有点老套)选项是告诉 Express 将 text/plain 请求解析为 JSON.这允许您将 JSON 字符串作为简单请求发送,这也可以避免飞行前 OPTIONS 请求,从而降低整体网络流量...

Another (slightly hacky) option is to tell Express to parse text/plain requests as JSON. This allows you to send JSON strings as simple requests which can also avoid a pre-flight OPTIONS request, thus lowering the overall network traffic...

app.use(express.json({
  type: ['application/json', 'text/plain']
}))

app.use 最终代码块中添加了结束括号.

Added ending parenthesis to app.use final code block.