node.js - React FormData() 显示正确的有效负载但收到 400 错误请求
问题描述
我正在使用对new FormData()
. 网络选项卡显示有效负载是正确的。在控制台中,我收到以下错误:
{message: "Blog validation failed: title: Path `title` is required., postBody: Path `postBody` is required."}
但是,在 network 选项卡中,它显示正在发送 title 和 postBody 字段:
服务器是用 nodejs 编写的,并且使用的是 mongodb。测试时所有路由都在后端工作。使用 .rest 文件测试数据时,数据发布得很好,但我还是节点新手,所以我也会发布我的处理程序以用于发布路由:
router.post('/', async (req, res) => {
const blogPost = new Blog({
title: req.body.title,
author: req.body.author,
postBody: req.body.postBody,
postDate: req.body.postDate
})
try {
const newPost = await blogPost.save();
res.status(201).json(newPost);
} catch (err) {
res.status(400).json({ message: err.message })
}
})
就像我说的,当使用 .rest 文件直接调用此路由时,一切正常。
这是我在前端的表单提交处理程序:
handleSubmit = (event) => {
event.preventDefault();
const data = new FormData(event.target);
console.log(event.target);
console.log(data);
console.log(event.target.postBody.value);
fetch('http://localhost:4000/blog', {
method: 'POST',
mode: 'cors',
body: data
})
.then(res => res.json())
.then(err => console.error(err))
}
也许我误解了new FormData()
?
解决方案
好的,所以当我添加 body-parser 时,我仍然遇到同样的错误。不知道我做错了什么。然而,为了我自己的时间来处理这个问题,我想出了另一个解决方案。我通过在我的节点应用程序中接受 jsonapp.use(express.json())
最后,我只需要发送带有内容类型的标题,我不再使用FormData()
. 我更新的表单提交处理程序(工作):
handleSubmit = (event) => {
event.preventDefault();
const data = new FormData(event.target);
const body = event.target.postBody.value;
const postTitle = event.target.title.value;
console.log(event.target);
console.log(data);
console.log(event.target.postBody.value);
fetch('http://localhost:4000/blog', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
mode: 'cors',
body: JSON.stringify({
title: postTitle,
postBody: body
})
})
.then(res => res.json())
.then(err => console.error(err))
}
这对我有用,这就是我现在要做的,以便我可以继续前进,但是,它仍然不能回答为什么我之前尝试的 formData() 方法不起作用,即使在使用 body-parser 之后也是如此建议在这里。
推荐阅读
- java - 当我在mybatis中使用insert、update(DML statements)时,如何确定它们执行成功?
- regex - RegEx 不验证没有第一个零的十进制数
- php - 为什么我的 $items 没有一组 $item?Laravel 8 电子商务
- performance - 为什么在测试具有特定类型签名的 Functor 实例时 QuickCheck 需要很长时间?
- nginx - nginx反向代理重定向到http而不是https
- angular - 实时数据库对列表进行排序
- c# - 具有分布式图节点的有向无环图
- ocr - 在谷歌云视觉 API 中调用 client.text_detection() 获取 TypeError: type object got multiple values for keyword argument 'features'
- python - Python:为自定义类方法实现保留“cls”注释
- c# - 在 C# 中运行此程序时出现错误:方法 'Movies' 没有重载需要 '0' 参数。我需要一种方法来做到这一点