[英]Empty body in fetch post request
i'm struggling with the fetch API in javascript.我正在为 javascript 中的 fetch API 苦苦挣扎。 When i try to POST something to my server with fetch, the request body an empty array.
当我尝试使用 fetch 将某些内容发布到我的服务器时,请求正文是一个空数组。 But when i use Postman it works... Here is my server code in NodeJS :
但是当我使用 Postman 时它可以工作......这是我在 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)
and here is my client:这是我的客户:
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)
})
The problem is that on the SERVER side, the req.body is empty.问题是在 SERVER 端,req.body 是空的。 Can someone help me?
有人能帮我吗? Thank you !
谢谢 !
The issue is问题是
mode: 'no-cors'
From the documentation ...从文档...
Prevents the method from being anything other than HEAD, GET or POST, and the headers from being anything other than simple headers
防止方法不是 HEAD、GET 或 POST 之外的任何内容,以及标题不是简单标题之外的任何内容
The simple content-type header restriction allows简单的内容类型头限制允许
text/plain
, text/plain
,application/x-www-form-urlencoded
, and application/x-www-form-urlencoded
,和multipart/form-data
This causes your nicely crafted Content-Type: application/json
header to become content-type: text/plain
(at least when tested through Chrome).这会导致您精心制作的
Content-Type: application/json
标头变为content-type: text/plain
(至少在通过 Chrome 测试时)。
Since your Express server is expecting JSON, it won't parse this request.由于您的 Express 服务器需要 JSON,因此它不会解析此请求。
I recommend omitting the mode
config.我建议省略
mode
配置。 This uses the default "cors"
option instead.这将使用默认的
"cors"
选项。
Since your request is not simple , you'll probably want to add some CORS middleware to your Express server.由于您的请求并不简单,您可能希望向 Express 服务器添加一些CORS 中间件。
Another (slightly hacky) option is to tell Express to parse text/plain
requests as JSON.另一个(有点hacky)选项是告诉Express 将
text/plain
请求解析为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...这允许您将 JSON 字符串作为简单的请求发送,这也可以避免飞行前的
OPTIONS
请求,从而降低整体网络流量...
app.use(express.json({
type: ['application/json', 'text/plain']
}))
EDIT: Added ending parenthesis to app.use
final code block.编辑:向
app.use
最终代码块添加了结束括号。
Please see document mode , no-cors
mode only send simple headers.请参阅文档 模式,
no-cors
模式只发送简单的标题。 So the content-Type is changed to text/html;
所以将content-Type改为
text/html;
instead of application/json
so your server can't recognize body format and return empty.而不是
application/json
因此您的服务器无法识别正文格式并返回空。
Remove mode: 'no-cors',
and you should be fine.删除
mode: 'no-cors',
你应该没问题。
To complement the excellent answers that mentioned removing the mode: 'no-cors'
option, and if you don't feel like adding a CORS middleware to Express, you may just want to handle "pre-flight" requests under an OPTIONS
block:为了补充提到删除
mode: 'no-cors'
选项的优秀答案,如果您不想向 Express 添加CORS 中间件,您可能只想在OPTIONS
块下处理“预检”请求:
app.options('*', (req, res) => {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type'); // Add other headers here
res.setHeader('Access-Control-Allow-Methods', 'POST'); // Add other methods here
res.send();
});
Another nice answer here : https://www.vinaygopinath.me/blog/tech/enable-cors-with-pre-flight/另一个不错的答案: https : //www.vinaygopinath.me/blog/tech/enable-cors-with-pre-flight/
Hope this helps!希望这可以帮助!
none seems to work for me I solved this issue using middleware似乎没有一个对我有用我使用中间件解决了这个问题
app.use(restify.plugins.bodyParser());
or或者
app.use(multer().array())
Many of the above answers weren't resolving my issue, so anyone running into this problem may need to do what I needed to do and enable their app
to be capable of reading JSON in a body, as the app can't do that by default which is what's leading to the empty body上述许多答案都没有解决我的问题,因此遇到此问题的任何人都可能需要做我需要做的事情,并使他们的
app
能够读取主体中的 JSON,因为该应用程序无法通过default 这是导致空体的原因
I resolved this by adding:我通过添加解决了这个问题:
app.use(bodyParser.json());
POST/PUT requests sent the body no problem after adding this one line添加这一行后,POST/PUT 请求发送正文没有问题
Technically, the bodyParser
module is deprecated, so this isn't the most ideal solution, but if adding the above line to your code makes it work then you at least know your issue lies in the way your app can parse/read JSON in a body从技术上讲,
bodyParser
模块已被弃用,因此这不是最理想的解决方案,但如果将上述行添加到您的代码中使其工作,那么您至少知道您的问题在于您的应用程序可以解析/读取 JSON 的方式身体
If you want to get response using fetch consider to use res.send : 如果您想使用fetch获取响应,请考虑使用res.send :
app.post('/api', function (req, res) {
res.send(req.body)
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.