来自 FormData 的 ExpressJS PUT 请求正文数据始终为空

问题描述 投票:0回答:1

每次我通过 React 上的表单向 API 提交 PUT 请求时,请求正文最终总是为空,并且我不完全确定数据发生了什么。

const handleEdit = async (e) => {
        e.preventDefault()
        console.log("Submitted")

        const formData = new FormData()
        formData.append("author", author)
        formData.append("title", title)
        formData.append("image", image)
        formData.append("body", body)
    
        // alert(author + " " + title + " " + image + " " + body)
    
        const response = await fetch(`http://localhost:3002/api/blogs/put/${selectedId}`,{
            method: "PUT",
            body: formData,
        })
    
        if (response.status === 200) {
          alert("Updated")
          window.location.reload()
        } else {
          console.log("Error")
        }
    }

代码在表单提交后运行。我已确认附加数据不为空并且具有所有正确的值。

这是请求处理程序:

app.put("/api/blogs/put/:id", (req, res) => {
    const id = req.params.id;
    
    const author = req.body.author;
    const title = req.body.title;
    const image = req.body.image;
    const body = req.body.body;

    console.log(req)

    db.query("UPDATE blogs SET author = ?, title = ?, image = ?, body = ? WHERE id = ?", [author, title, image, body, id], (err, result) => {
        if (err) {
            console.log(err);
            res.status(500).send('Error updating blog post');
        }
        
        res.send(result);
    })
})

当我 console.log(req) 时,主体:{} 为空。

没有错误,请求成功通过,只是将我的 SQL 服务器上的所有字段更新为 null。

提交表单时,所有必填字段都附加到 formData 中,我已经确认这些字段不为空,然后一旦请求通过,它到达处理程序,然后一切都为空,正文为空。

我还尝试将 processData: false、contentType: false 添加到请求中(单独或两者)。

控制台或我所看到的任何内容都没有错误。

reactjs node.js express null form-data
1个回答
0
投票
To resolve this issue you can add enctype="multipart/form-data" and method="PUT" to your form in your React component. 
 Like this:

 <form onSubmit={handleEdit} encType="multipart/form-data">
  //your code....
    <button type="submit">Submit</button>
</form>

I hope this will be helpful for you .
© www.soinside.com 2019 - 2024. All rights reserved.