首页 > 解决方案 > Vuejs axios如何用键传递数组?

问题描述

我正在尝试将一些数据作为“offer”数组发布到我的 Laravel 后端:

这就是它在邮递员中的外观和工作方式:keys: offer[title] , offer[description] , offer[author_user_id]

现在使用 axios 我尝试了类似的方法:

 offer: {
         title: this.input.title,
         description: this.input.description,
         author_user_id: id,
         }

也尝试过: [key=>val]和例如offer.title: value,但也失败了。

它应该是什么样子?

编辑:

this.axios.post('http://api.wip/api/offer/store', {
                    offer: {
                        title: this.input.title,
                        description: this.input.description,
                        author_user_id: id,
                    },
                    category: 2
                }, {
                    headers: {
                        'Authorization': 'Bearer ' + token,
                        'Content-Type': 'application/x-www-form-urlencoded',
                        'X-Requested-With': 'application/json'
                    }
                })
                .then(function () {
                })
                .catch(function () {
                });

在我的控制台中,我可以看到它被发送为:

{"offer":{"title":"asd","description":"asd","author_user_id":"2"},"category":2}: 

我从服务器收到 500 错误,并从 Laravel 响应它期望数据是数组。

"message": "Argument 1 passed to Illuminate\\Database\\Eloquent\\Builder::create() must be of the type array, null given, called in D:\\wamp64\\www\\apitest\\vendor\\laravel\\framework\\src\\Illuminate\\Support\\Traits\\ForwardsCalls.php on line 23",

正如我所说,它适用于邮递员,但不能通过 axios 使它工作

Laravel 控制器:

 public function store(Request $request) {
        $offer = Offer::create($request->input('offer'));
        $offer->category()->sync($request->input('category'));
        $offer->save();

        return response()->json($offer);
    }

标签: arrayslaravelvue.jsaxios

解决方案


Boussadjra Brahim 是对的,问题出在后端但它是由从前端发送空值引起的,所以我们必须看看前端。

第一件事是使用 {} 意味着你正在创建对象,[] 是数组和 laravel 创建方法只接受数组

输入本身就是一个数组,因为您正在使用(点)访问它的键,那么为什么不将要约设置为整个数组,然后在后端将它们分开呢?像这样

axios.post('http://api.wip/api/offer/store', {
                    offer:this.input,
                 author_user_id: id,
                    category: 2
                },

在您的后端,您可以像这样访问它们:

$title = $request->offer['title'];

最后一件事,当你使用 create 方法时,键必须与数据库中的列名相同,否则会抛出错误!希望能帮助到你


推荐阅读