传递对象时Axios POST请求不起作用

asl*_*tor 5 vue.js axios

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

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);
});
Run Code Online (Sandbox Code Playgroud)

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

var_dump($_POST);
Run Code Online (Sandbox Code Playgroud)

但这将返回空数组。

con*_*exo 4

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

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

  • 只有 Qs.stringify 有效。JSON.stringify() 不起作用。不知道为什么。 (2认同)