获取帖子请求中的空身体 [英] Empty body in fetch post request
问题描述
我正在努力使用javascript中的fetch API。
当我尝试使用fetch将某些东西发布到我的服务器时,请求体是一个空数组。但是,当我使用Postman时,它的工作原理...
这是我在NodeJS中的服务器代码:
i'm struggling with the fetch API in javascript. When i try to POST something to my server with fetch, the request body an empty array. But when i use Postman it works... Here is my server code in NodeJS :
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)
})
问题是在SERVER端,req.body是空的。
有人能帮帮我吗?谢谢!
The problem is that on the SERVER side, the req.body is empty. Can someone help me? Thank you !
推荐答案
问题是
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
简单的内容类型标题限制允许
The simple content-type header restriction allows
-
text / plain
, -
application / x-www-form-urlencoded
, -
multipart / form-data
text/plain
,application/x-www-form-urlencoded
, andmultipart/form-data
这会让您精心制作 Content-键入: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.
I建议省略模式
config。这使用默认的cors
选项。
I recommend omitting the mode
config. This uses the default "cors"
option instead.
自您的请求不是 simple ,您可能希望向Express服务器添加一些 CORS中间件。
另一个(略微hacky)选项是告诉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']
})
这篇关于获取帖子请求中的空身体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!