赞
踩
此环节带领大家了解axios,如果熟练的同学可直接移步到下面的封装环节哦!
官方解释:Axios 是一个基于 promise 的 HTTP 库,可以用在浏览器和 node.js 中。
axios最大的亮点就是它支持了ES6里的 Promise Api,感兴趣的同学可以去看一看阮一峰写的 《ES6入门教程》,传送门:ES6入门教程
从浏览器中创建 XMLHttpRequests
从 node.js 创建 http 请求
支持 Promise API
拦截请求和响应
转换请求数据和响应数据
取消请求
自动转换 JSON 数据
客户端支持防御 XSRF
使用npm
$ npm install axios
使用yarn
$ yarn add 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;
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。