Axios POST 请求在传递对象时不起作用 [英] Axios POST request not working when passed object
问题描述
我正在尝试使用 axios 在 vue js 应用程序中对本地 API 执行发布请求,并且响应返回空数据.API 上的 post 请求使用 Postman 工具工作正常.下面是我的代码
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屋!