获取 POST 请求中的空正文

Empty body in fetch POST request(获取 POST 请求中的空正文)

本文介绍了获取 POST 请求中的空正文的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为 Javascript 中的 fetch API 苦苦挣扎.当我尝试使用 fetch 方法将某些内容发布到我的服务器时,请求正文包含一个空数组.但是当我使用 Postman 时,它可以工作.这是我在 Node.js 中的服务器端代码:

I'm struggling with the fetch API in Javascript. When I try to POST something to my server with fetch method, the request body contains an empty array. But when I use Postman it works. Here is my server-side code in Node.js:

const express = require('express')
const app = express()
const port = 3000

app.use(express.json())
app.post('/api', function (req, res) {
    console.log(req.body)
})
app.listen(port)

这是我的客户端代码:

fetch('http://"theserverip":3000/api', {
    method: 'POST',
    headers: { "Content-Type": "application/json" },
    mode: 'no-cors',
    body: JSON.stringify({
        name: 'dean',
        login: 'dean',
    })
})
.then((res) => {
    console.log(res)
})

问题是 req.body 在服务器端是空的.

The problem is that the req.body is empty on server side.

推荐答案

问题是

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.

这篇关于获取 POST 请求中的空正文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:获取 POST 请求中的空正文

基础教程推荐