其实吧感觉看官网就挺好的:http://www.axios-js.com/zh-cn/docs/ 哈哈
npm install axios --save
axios({
//请求地址
url:'/user',
//请求类型
method:'post',
//请求根目录
baseURL:'http://xxx.xx.xx.x/api',
// URl传递参数
params:{id:2},//get请求时用
data:{key:''},//post请求时用
//自定义请求头
headers:{'x-Requested-With':'XMLHttpRequest'},
//设置超时时间
timeout:5000,
//跨域是否带Toten
withCredentials:false,
//身份信息验证
auth:{uname:'',pwd:''},
//具体可以看这个官网链接:http://www.axios-js.com/zh-cn/docs/
})
普通的使用
axios({
url:'http://xxx.xx.xx.x/api'
method:'get', //get是默认的
}).then(res=>{
console.log(res.data);
})
并发
all(这个方法就是里面全部的请求都完成了再将各个请求的结果以数组的形式返回给你)
axios.all([axios({
baseURL:'http://xxx.xx.xx.x', //设置默认api前缀
url:'/api'
timeout:5,//设置请求超时时间
}),axios({
baseURL:http://xxx.xx.xx.x',
url:'/api'
params:{
type:'sell',
page:5000 //毫秒
}
})]).then(axios.spread((res1,res2)=>{
console.log(res1);
})
项目使用时建议封装
封装:先创建js文件axiosRequest
import axios from "axios";
//举个栗子(详细操作看官网:http://www.axios-js.com/zh-cn/docs/)
const req = (method, url, params) => {
return axios({
method: method,
url: url,
// headers: {
// 'Content-Type': 'application/x-www-form-urlencoded',
// token: localStorage.getItem('logintoken')
// },
data: params,
traditional: true,
transformRequest: [
function(data) {
let ret = ''
for (let it in data) {
ret +=
encodeURIComponent(it) +
'=' +
encodeURIComponent(data[it]) +
'&'
}
return ret
}
]
}).then(res => res.data);
};
//简单的封装(再举个栗子)
const getdata =(url,data)=>{
const instance =axios.create({
baseURI:'http://http://xxx.xx.xx.x',
})
return instance({
url:url,
params:data
})
}
//将要使用的封装方法导出
export default getdata
要使用的位置
//导入import getdata from './axiosFun'
getdata('/api',{id:parmas}).then(res=>{
console.log(res)
}).catht(err=>{
console.log(err)
})
可以再封装 (再创建一个js文件 baes)
export const dataapi =(parmas)=>{return getdata('/api',{id:parmas})}
export const dataapi2 =(parmas)=>{return getdata('/api',{id:parmas})}
要使用的位置
import {dataapi} from "../../api/base";
dataapi("2").then(res=>{
console.log(res);
}).catch(err=>{
console.log(err);
})