事件描述
在vue中引入了axios,向后端发起post请求。后端始终无法获得我post的几条数据。报错全部显示undefined
原本的写法
import axios from 'axios'
axios.post('/group8Interface/register.php',{
username:'xx',
password:'xx',
email:'xx',
author:'xx'
}) .then(function (response) {
console.log(response);
})
正常情况下就应该在控制台打印出后端的结果了,但是priview始终报错4个值全都是undefined
改进
使用axios中的createElement,将要传送的数据stringfy ,并设置请求头
import axios from 'axios'
import Qs from 'qs'
var axiosAjax = axios.create({
baseURL:'/', //baseURL会自动加载url前面,根据自己需求配置,详情见官方文档
transformRequest: [function (data) { //这里的data就是后面.post方法中的第二个参数,不需要再在vue的data中定义了
data = Qs.stringify(data); // 把要发送给后端的数据,通过Qs.stringify转换为表单查询参数
return data;
}],
headers:{
'Content-Type':'application/x-www-form-urlencoded'
}
})
axiosAjax.post('/group8Interface/register.php',{
username:'xx',
password:'xx',
email:'xx',
author:'xx'
}) .then(function (response) {
console.log(response);
})
这个解决方法也是我从网上搜的,欢迎意见和建议