简体   繁体   English

如何使用 axios 将图像和文本放入 api

[英]How to PUT an image and text to api using axios

        const fd = new FormData()
        fd.append('pp', this.state.image)
        fd.append('username', this.state.user.username)
        fd.append('email', this.state.user.email)
        fd.append('bio', this.state.user.bio)
        console.log(this.state.user)
        axios.put(`http://127.0.0.1:8000/users/profile/update/${this.state.id}/`, fd, {
            headers: {
                'Content-Type': 'multipart/form-data'
            }
        })

The above code is resulting in a 400 bad request, but when I try in postman it works.上面的代码导致 400 错误请求,但是当我在 postman 中尝试时它可以工作。 So I believe it is a misuse of formdata can someone help.所以我相信这是对表单数据的滥用,有人可以帮忙。 By the way whenever I only update the image it works, but once I update one of the text fields it doesn't.顺便说一句,只要我只更新图像,它就可以工作,但是一旦我更新了其中一个文本字段,它就不会了。

The name of your request body parameters in axios aren't strings. axios 中的请求正文参数的名称不是字符串。 They are simply the name of the field.它们只是字段的名称。 So your request body should actually look like this:-因此,您的请求正文实际上应该如下所示:-

fd = {
  pp : this.state.image,
  username : this.state.user.username,
  email : this.state.user.email,
  bio : this.state.user.bio
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM