【问题标题】:Axios send formData in controller return object objectaxios在控制器中发送formData返回object对象
【发布时间】:2020-07-31 07:01:59
【问题描述】:

//Vuejs2 //Laravel v7.x

我求助于你,因为我正在阻止,我找不到解决方案。 我想在我的控制器中恢复我的对象中的数据。 在我的 View.vue 中,我发布了一个 axios 帖子

     data() {
        return {
          customer: {
             name: 'abc',
             login: 'def'
          },
          file: null
        }
    },methods: {
        submit(){
            let formData = new FormData();
            formData.append("customer", this.customer);
            formData.append("file", this.file);

            axios.post('/project/new',
                        formData, {
                            headers: {
                                "Content-Type": "multipart/form-data"
                            }
                        }).then(data => {
                        console.log(data.data);
                    });
        }
    }

我在我的控制器中收集这样的东西

public function postProject(Request $request)
{
    return $request->customer;  //return [Object Object]
    return $request->customer->name;  //return Trying to get property 'name' of non-object
    return $request->customer['name']; //return Illegal string offset 'name'
    return $request->file;  //return [Object Object]
}

谢谢帮助。祝你有美好的一天。

【问题讨论】:

    标签: javascript laravel vue.js vuejs2 axios


    【解决方案1】:

    您不能使用 .append 将对象添加到您的 FormData。

    查看https://developer.mozilla.org/en-US/docs/Web/API/FormData/append 方法只接受USVString 或Blob 作为值。其他所有内容都转换为 String。

    Javascript 中标准对象的字符串表示形式是[object Object]

    您可以尝试JSON.stringify(this.customer) 将其转换为 JSON 表示形式。

    【讨论】:

    • 我真的要谢谢你!它终于奏效了!如果我发送文件,我需要 JSON.stringify 吗?
    • 要发送文件,您必须将 File 类的实例传递给 FormData developer.mozilla.org/de/docs/Web/API/File
    【解决方案2】:

    试试 $request->get('customer') 或 $request->input('customer')

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多