[英]How to get JSON in Laravel from vue.js axios POST?
我在 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 Controller:
$test = json_decode($request->getContent(), true);
$test = $test['payment_type'];
return response($test);
但是当我执行这个 POST 请求时,我收到了空数据作为响应。
另外,我尝试用 Postman 检查我的 API,它工作正常。 我只是发送请求,然后 go 到 F12 > 网络 > 找到我的请求并复制请求有效负载源数据。 然后我将其粘贴到 Postman 正文(原始,json)中,并使用此数据向相同的 url(http://localhost:8000/api/orders)发出请求,并按预期返回“现金”。 所以我决定,这是 vue.js 或 axios 问题,但我不知道如何解决这个问题。 谢谢!
更新我已经尝试从 axios、JSON.stringify 订单中删除 Content-Type 并得到相同的结果 - 响应中的空数据。
我认为,在 axios 中使用订单之前,您应该对 JSON 数据进行字符串化:
let order = JSON.stringify(this.$store.state.order.order);
一些评论后的第二部分答案:
您确定路由文件吗? I would call the controller from the web.php file (same folder) with a declared function (for example mytest ), like this:
Route::post('/api/products', 'ProductController@mytest');
并将您的 controller 逻辑放入 function 中:
public function mytest()
{
$test = json_decode($request->getContent(), true);
$test = $test['payment_type'];
return response($test);
}
如果这不起作用(也与 JSON.stringify 结合使用),我唯一的想法是您的“非常简单的 Laravel 控制器”中的错字;)...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.