首页 > 解决方案 > 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()?

标签: node.jsreactjsmongodbforms

解决方案


好的,所以当我添加 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 之后也是如此建议在这里。


推荐阅读