有了axios 和 async await 这样的封装好的组件和语法糖,简直让现在的前端开发者轻松许多,大部分情况都不需要再手写底层代码了。
这里直接用代码来把axios的常用方式罗列一下,当然在实际开发中,axios组件还是需要封装的。
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script>
axios({
url: 'http://localhost:8888',
method: 'get',
params: {
id: 1,
name: "张三"
}
}).then(
res => console.log(res + '这是数据'),
reason => console.log('数据请求失败')
);
//简单写法
axios.get('http://localhost:8888')
.then(
res => console.log(res + '这是数据'),
// reason => console.log('简写的数据请求失败')
)
.catch(
error => {
console.log("请求超时")
console.log(error);
});
//并发请求
axios.all([
axios.get('http://localhost:8888'),
axios.get('http://localhost:8888')
]).then(
axios.spread((res1, res2) => {
//两个请求都完成后自动拆分成两个参数
console.log(res1);
console.log(res2);
}))
.catch(err => console.log('并发请求超时'));
//全局配置
axios.defaults.baseURL = "http://localhost:8888"
axios.defaults.timeout = 2000;
axios.get('xxxxx').then(res => {
console.log(res);
})
.catch(err => console.log(err));
// axios实例封装
let newAbc = axios.create({
baseURL: "http://localhost:8888",
timeout: 3000
});
let newAbc2 = axios.create({
baseURL: "http://localhost:8881",
timeout: 3000
});
newAbc({
url: 'getthedateXXXX'
}).then(res => console.log(res))
.catch(err1 => console.log('实例化请求错误1' + err1));
newAbc2({
url: 'getthedateXX123'
}).then(res => console.log(res))
.catch(err2 => console.log('实例化请求错误2' + err2));
//axios拦截器 请求方向
axios.interceptors.request.use(
config => {
console.log('进入了拦截器');
return config;
},
error => console.log("请求失败方向")
);
axios.get("http://localhost:8881").then(res => console.log(res));
//响应方向
axios.interceptors.response.use(
config => {
console.log('进入了拦截器');
return config.data;//返回数据
},
error => console.log("响应失败方向")
);
axios.get("http://localhost:8881").then(res => console.log(res));
</script>