【问题标题】:How to get JSON in Laravel from vue.js axios POST?如何从 vue.js axios POST 在 Laravel 中获取 JSON?
【发布时间】:2021-06-17 13:05:18
【问题描述】:

在我的 Laravel 后端使用 axios 从 vuex 接收 JSON 数据时遇到一些问题。

我有这样的 vuex 存储,我想在点击时将其发送到后端。

 order: {
        delivery_id: null,
        user_id: null,
        is_active: true,
        bill: null,
        name: null,
        surname: null,
        father_name: null,
        phone: null,
        payment_type: 'cash',
        delay: null,
        cashback_paid: null,
        card: null,
        payment_screenshot: null,
        cart: null,
    }

在 vue 组件中我有这个方法:

sendOrder() {
  let order = this.$store.state.order.order;
  console.log(order)

  axios
    .post('/api/products', order, {
      header: {
        'Content-Type': 'application/json'
      }
    })
    .then((response) => {
      console.log(response);
    })
    .catch((error) => {
      console.log(error);
    })
}

这是我非常简单的 Laravel 控制器:

$test = json_decode($request->getContent(), true);

$test = $test['payment_type'];

return response($test);

但是当我执行这个 POST 请求时,我收到了空数据作为响应。

另外,我尝试使用 Postman 检查我的 API,它工作正常。我只是发送请求,然后转到 F12 > 网络 > 找到我的请求并复制请求有效负载源数据。然后我将它粘贴到 Postman 正文 (raw, json) 并使用此数据向相同的 url (http://localhost:8000/api/orders) 发出请求,并按预期返回“现金”。所以我决定,这是 vue.js 或 axios 的问题,但我不知道如何解决这个问题。谢谢!

更新 我已经尝试从 axios、JSON.stringify 订单中删除 Content-Type 并得到相同的结果 - 响应为空数据。

【问题讨论】:

    标签: javascript laravel vue.js axios vuex


    【解决方案1】:

    我认为,在 axios 中使用 order 之前,您应该对 JSON 数据进行字符串化:

    let order = JSON.stringify(this.$store.state.order.order);
    

    一些cmets之后的第二部分答案:

    您确定路由文件吗?我会使用声明的函数(例如 mytest)从 web.php 文件(同一文件夹)调用控制器,如下所示:

    Route::post('/api/products', 'ProductController@mytest');
    

    并将您的控制器逻辑放入该函数中:

    public function mytest()
    {
        $test = json_decode($request->getContent(), true);
        $test = $test['payment_type'];
        return response($test);
    }
    

    如果这不起作用(也与 JSON.stringify 结合使用),我唯一的想法是您的 “非常简单的 Laravel 控制器”中的一个错字 ;)...

    【讨论】:

    • 感谢您的回复。我已经尝试过了,但结果相同。我编辑了我的问题并添加了一个更新 - “更新我已经尝试从 axios、JSON.stringify 订单中删除 Content-Type 并且得到了相同的结果 - 响应中的空数据。”
    • 你的 console.log(order) 输出了什么?你的路由文件(可能是'routes/web.php')对'/api/products'有什么作用?
    • 我的 console.log 输出:{ "delivery_id": 4, "user_id": 1, "is_active": true, "bill": '00-54753', "name": 'Name', "surname": 'Surname', "father_name": 'Name', "phone": '+7777777', "payment_type": "cash", "delay": null, "cashback_paid": null, "card": null, "payment_screenshot": null, "cart": null } 和我的 'routes/api.php' Route::resource('/products', ProductController::class); 我在主帖中的控制器代码(没有足够的符号)
    • 哦,多么愚蠢的错误。我使用了错误的 url '/api/products' 而不是 '/api/orders'。很抱歉浪费了您的时间。
    猜你喜欢
    • 1970-01-01
    • 2018-09-08
    • 2020-07-22
    • 2018-07-11
    • 2020-01-21
    • 1970-01-01
    • 2014-01-11
    • 2019-09-29
    • 2018-01-17
    相关资源
    最近更新 更多