vue使用axios和qs完成向后台发出post请求

Vue.js使用axios向后台发出post请求和获取数据一样,可以直接调用函数

1
2
//在需要交互的.vue文件中添加引用
import axios from 'axios';
1
2
3
4
5
6
7
8
9
10
11
12
13
//然后在methods使用post方法发出请求
methods: {
postData(){
axios.post('url', {
id: '1',
name: 'user1'
}).then((response)=>{
//do something with the response
}).catch((error)=>{
console.log(error);
})
}
}

但是有时候使用这种方法后台有可能接收不到数据,因为数据没有序列化,所以这个时候可以使用qs插件地址库对数据进行编码,将axios发送的数据格式转换为form-data格式

1
2
3
//安装axios的时候会默认安装qs
//在需要交互的.vue文件中添加引用
import qs from 'qs';
1
2
3
4
5
6
7
8
9
10
11
12
13
14
//然后在methods使用post方法发出请求
methods: {
postData(){
var data = qs.stringify({
id: '1',
name: 'user1'
});
axios.post('url', data}).then((response)=>{
//do something with the response
}).catch((error)=>{
console.log(error);
})
}
}