传递对象时,Axios POST请求不起作用 [英] Axios POST request not working when passed object

查看:110
本文介绍了传递对象时,Axios POST请求不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用axios在vue js应用程序中向本地API发出发布请求,并且响应返回空数据.使用Postman工具可以很好地执行API上的发布请求.下面是我的代码

I am trying to do a post request in a vue js app using axios to a local API and the response is returning empty data. The post request on API is working fine using Postman tool. Below is my code

var the_data = {
    title: 'This is title',
    description: 'this is description'
}

axios.post('/api/snippets/insert', the_data)
.then(function (response) {
    console.log(response);
})
.catch(function (error) {
    console.log(error);
});

在API端,我正在使用一个简单的PHP脚本,并使用此代码打印整个$ _POST请求数据

On the API end, I am using a simple PHP script and printing whole $_POST request data using this code

var_dump($_POST);

但这将返回空数组.

推荐答案

我也遇到了这个问题.Axios不会以您期望的形式发送POST数据.您需要类似 http://github.com/ljharb/qs 之类的东西,然后使用 axios.post('/api/snippets/insert',Qs.stringify(the_data)).请注意,此基于cdnjs的版本使用 Qs ,而不是 qs .

I was running into this as well. Axios does not send the POST data in the form you're expecting. You need something like http://github.com/ljharb/qs and then use axios.post('/api/snippets/insert', Qs.stringify(the_data)). Please note this build on cdnjs uses Qs, not qs.

qs 的替代方案例如 JSON.stringify()或jQuery的 $.param().

Alternatives to qs would be e.g. JSON.stringify() or jQuery's $.param().

这篇关于传递对象时,Axios POST请求不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆