一、认识axios
此环节带领大家了解axios,如果熟练的同学可直接移步到下面的封装环节哦!
1、axios是什么?
官方解释:Axios 是一个基于 promise 的 HTTP 库,可以用在浏览器和 node.js 中。
2、为什么要用axios?
axios最大的亮点就是它支持了ES6里的 Promise Api,感兴趣的同学可以去看一看阮一峰写的 《ES6入门教程》,传送门:ES6入门教程
特性
从浏览器中创建 XMLHttpRequests
从 node.js 创建 http 请求
支持 Promise API
拦截请求和响应
转换请求数据和响应数据
取消请求
自动转换 JSON 数据
客户端支持防御 XSRF
二、封装axios
使用npm
$ npm install axios
使用yarn
$ yarn add axios
在src里面创建uitl文件并创建一个js文件

在这个js文件里面写axios封装
import axios2 from "axios";
import Vue from "vue";
async function http2(options,withLoading = true) {
options.headers = {Authorization:sessionStorage.getItem('token')};
if (withLoading) Vue.prototype.$weiLoading.open(); //开启loading
await new Promise(resolve => setTimeout(resolve,500));
return axios2(options)
.then(res => {
if (res.status === 200) {
let result = res.data;
switch (result.code) {
case 200:
if (withLoading)Vue.prototype.$weiLoading.close();
return result.data;
case 199:
case 500:
case 401:
sessionStorage.removeItem('token');
sessionStorage.removeItem('name');
if (!sessionStorage.removeItem('token')) {
// Vue.prototype.$weiLoginAlert();
// Vue.prototype.$weiAlert('登录已过期');
}
case 404:
throw new Error(result.msg); // 有错,显示抛出异常直达下面的catch
}
} else {
throw new Error(res.statusText);
}
})
.catch(function (error) {
if (withLoading) Vue.prototype.$weiLoading.close();
// Vue.prototype.$weiAlert('登录已过期');
return Promise.reject(error.message);
})
}
export default http2;
在mian.js里面把https添加到vue的prototype里面

在src里面创建api文件并且创建一个index.js文件

在这个index.js文件里面写请求


最后在文件里面进入就可以用了

