【问题标题】:Axios formData with image is sending empty array带有图像的 Axios formData 正在发送空数组
【发布时间】:2020-10-03 01:20:07
【问题描述】:

我在后端的配置文件路由中有一个 put 方法,我需要令牌身份验证,因此为了获得授权,我必须通过标头传递令牌,我收到一个错误,因为由于某种原因它正在发送一个空的 formData当我在后端记录请求时。

我用邮递员测试了后端,一切都按预期工作,所以这不是后端问题,我从前端发出的请求完全有问题,但我不知道如何处理,有什么线索吗?

profile_update() {
            let params = {
                email: this.profile.email,
                password: this.profile.password,
                coin: this.profile.coin,
                phone_country: this.profile.phone_country,
                phone_area: this.profile.area_code,
                phone_number: this.profile.number,
                first_name: this.profile.first_name,
                last_name: this.profile.last_name,
                date_of_birth: this.profile.date_of_birth,
                gender: this.profile.gender,
                city_id: this.profile.city,
                wants_to_change_password: this.profile.wants_to_change_password,
                state_id: this.profile.state,
                city_id: this.profile.city
            }

            let headers = {
                'Authorization': 'Bearer' + this.token
            }

            let formData = new FormData();
            formData.append('profile-picture', this.profile.profile_picture)
            formData.append('data', params)
            formData.append('headers', headers)
            formData.append('_method', 'PUT')

            axios.put(`http://127.0.0.1:8000/api/profile`, formData, headers).then(res => {
                console.log(res)
            }).catch(e => {
                console.log(e)
            })
        }

【问题讨论】:

    标签: vue.js axios


    【解决方案1】:

    试试这个方法

    axios.put(`http://127.0.0.1:8000/api/profile`, {'profile-picture':this.profile.profile_picture}, {
      headers: {
        Authorization: 'Bearer ' + this.token,
        'content-type': 'multipart/form-data'
      }
    }).then(res => {
         console.log(res)
    }).catch(e => {
         console.log(e)
    })
    

    希望这可以解决您的问题。更多信息请阅读docs

    【讨论】:

    • 它仍然发送一个空数组
    • 尝试在标题中添加内容类型属性。我已经编辑了答案做检查
    • 还是空的
    • 所以,我尝试添加一个带有随机值的额外参数,通过删除 content-type: multipart/form-data 它发送参数但将图像作为空数组发送,我需要发送图像,似乎我不能为此使用 formdata,但不确定是 axios 问题还是服务器问题
    • 没关系,我必须做一个附加formData.append('method', '_PUT')的帖子请求我完全忘记了,我直接发出了一个put请求
    猜你喜欢
    • 1970-01-01
    • 2022-09-23
    • 1970-01-01
    • 2014-01-17
    • 2020-08-18
    • 2020-07-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多