- 创建vue项目
- 安装axios:npm install axios@0.18.0 --save
- 在使用axios的组件中导入,import axios from 'axios'
- res.data是返回的数据。
基本使用
params中写GET方法的传参,data中写POST方法的传参。
then函数请求成功后执行,catch函数,请求出错时使用。
axios({
//请求方式,'GET'或者'POST'
method: 'GET',
//请求地址
url: '',
//url中的查询参数,GET方法的传参
params: {},
//请求体参数,POST方法的传参
data: {}
}).then(res => {})
get传参
axios({
method: 'GET',
url: 'http://localhost/post',
params: {
id: 1
},
}).then(res => console.log(res)).catch(error => {
// 请求失败,处理错误信息
console.error(error);
});
post传参
axios({
method: 'POST',
url: 'http://localhost/post',
data: {
name: 'zs',
age: 20
},
}).then(res => console.log(res)).catch(error => {
// 请求失败,处理错误信息
console.error(error);
});
直接发起请求
//axios直接发起GET请求
axios.get('url地址', {
//GET参数
params: {}
})
//axios直接发起POST请求
axios.post('url地址', { //POST参数 })