VUE的axios对Promise的封装和拦截器

const prod = process.env.NODE_ENV !== "development";
const root = prod ? "/root" : "/root";
const timeout = 60000;
import axios from "axios";
import * as types from "./interceptors";
import router from "router";
import {
removeLocalStorage
} from "./utils";
import {
Message,
Loading
} from "element-ui";

/**
* @method axiosGet get方法请求
* @method axiosPost get方法请求
* @method axiosPut get方法请求
* @method axiosDelete get方法请求
* @param {string} url url后台路由地址
* @param {any} params 请求对接接口需要的数据
*/
//创建axios实例
const createdAxiosInstance = config => {
let instance, reqInterceptors, resInterceptors;
if (config) {
reqInterceptors = config.reqInterceptors;
resInterceptors = config.resInterceptors;
if (reqInterceptors || resInterceptors) {
instance = axios.create();
} else {
instance = axios;
}
if (reqInterceptors) {
types.interceptorsRequest(instance);
}
if (resInterceptors) {
types.interceptorsResponse(instance, config.exportFile);
}
} else {
instance = axios;
}
return instance;
};

function redirectLogin() {
removeLocalStorage("smoke_session_token");
vueInstance.$store.commit("RESET_STATE");
router.replace({
path: "/login",
query: {
redirect: router.currentRoute.fullPath
}
});
Message.error({
message: "登录已失效,请重新登录!"
});
if (window.stompClient) {
window.stompClient.disconnect();
delete window.stompClient;
}
}

/**
* @method axiosGet GET方法请求
* @param {*} url 请求地址
* @param {*} params 请求参数
* @param {*} config 配置
*/
export const axiosGet = (url, params, config) => {
const instance = createdAxiosInstance(config);
const loadingFlag = config.loading === undefined ? true : config.loading;
let loadingInstance;
loadingInstance = loadingFlag ?
Loading.service({
fullscreen: true,
text: "拼命加载中",
spinner: "el-icon-loading",
background: "rgba(0, 0, 0, 0.8)"
}) :
null;
return new Promise(resolve => {
instance({
method: "GET",
url: url,
params: params,
baseURL: root,
withCredentials: true,
timeout: timeout,
responseType: config.responseType
})
.then(res => {
loadingFlag ? loadingInstance.close() : null;
if (res.resultCode !== 11000) {
resolve(res);
} else {
redirectLogin();
}
})
.catch(() => {
loadingFlag ? loadingInstance.close() : null;
});
});
};

/**
* @method axiosPost POST方法请求
* @param {*} url 请求地址
* @param {*} params 请求参数
* @param {*} config 配置
*/
export const axiosPost = (url, params, config) => {
const instance = createdAxiosInstance(config);
const loadingFlag = config.loading === undefined ? true : config.loading;
let loadingInstance;
loadingInstance = loadingFlag ?
Loading.service({
fullscreen: true,
text: "拼命加载中",
spinner: "el-icon-loading",
background: "rgba(0, 0, 0, 0.8)"
}) :
null;
return new Promise(resolve => {
instance({
method: "POST",
url: url,
data: params,
baseURL: root,
timeout: timeout
// withCredentials: true
})
.then(res => {
loadingFlag ? loadingInstance.close() : null;
if (res.resultCode !== 11000) {
resolve(res);
} else {
redirectLogin();
}
})
.catch(() => {
loadingFlag ? loadingInstance.close() : null;
});
});
};

/**
* @method axiosPut PUT方法请求
* @param {*} url 请求地址
* @param {*} params 请求参数
* @param {*} config 配置
*/
export const axiosPut = (url, params, config) => {
const instance = createdAxiosInstance(config);
const loadingFlag = config.loading === undefined ? true : config.loading;
let loadingInstance;
loadingInstance = loadingFlag ?
Loading.service({
fullscreen: true,
text: "拼命加载中",
spinner: "el-icon-loading",
background: "rgba(0, 0, 0, 0.8)"
}) :
null;
return new Promise(resolve => {
instance({
method: "PUT",
url: url,
data: params,
baseURL: root,
withCredentials: true,
timeout: timeout
})
.then(res => {
loadingFlag ? loadingInstance.close() : null;
if (res.resultCode !== 11000) {
resolve(res);
} else {
redirectLogin();
}
})
.catch(() => {
loadingFlag ? loadingInstance.close() : null;
});
});
};

/**
* @method axiosDelete DELETE方法请求
* @param {*} url 请求地址
* @param {*} params 请求参数
* @param {*} config 配置
*/
export const axiosDelete = (url, params, config) => {
const instance = createdAxiosInstance(config);
const loadingFlag = config.loading === undefined ? true : config.loading;
let loadingInstance;
loadingInstance = loadingFlag ?
Loading.service({
fullscreen: true,
text: "拼命加载中",
spinner: "el-icon-loading",
background: "rgba(0, 0, 0, 0.8)"
}) :
null;
return new Promise(resolve => {
instance({
method: "DELETE",
url: url,
params: params,
baseURL: root,
withCredentials: true,
timeout: timeout
})
.then(res => {
loadingFlag ? loadingInstance.close() : null;
if (res.resultCode !== 11000) {
resolve(res);
} else {
redirectLogin();
}
})
.catch(() => {
loadingFlag ? loadingInstance.close() : null;
});
});
};
 
 
拦截器:
import { setLocalStorage, removeLocalStorage, getLocalStorage } from "./utils";
import { Message } from "element-ui";

/**
* @method interceptorsRequest http request 拦截器
* @param {Object} instance axios实例
* @param {Function} handle 拦截器操作函数
*/
export const interceptorsRequest = instance => {
// http request 拦截器
instance.interceptors.request.use(
config => {
const handle = () => {
// 判断是否存在token,如果存在的话,则每个http header都加上token
const s_session = getLocalStorage("smoke_session_token");
if (s_session) {
return s_session;
}
return null;
};
config.headers.token = handle();
return config;
},
err => {
return Promise.reject(err);
}
);
};

/**
* @method interceptorsRequest //http response 拦截器
* @param {Object} instance axios实例
* @param {Function} handle 拦截器操作函数
*/
export const interceptorsResponse = (instance, exportFile) => {
//http response 拦截器
instance.interceptors.response.use(
response => {
//对于文件下载
if (exportFile) {
if (response.data.type === "application/json") {
//闭包把值传出去,通过类型分辨blob和json
return () => {
return response.data;
};
} else {
return response.data;
}
}
const session_token = response.headers.token;
if (session_token) {
setLocalStorage("smoke_session_token", session_token);
}
return response.data;
},
error => {
if (error.response) {
const handle = error => {
switch (error.response.status) {
case 404:
Message.error({
message: "请求资源不存在!"
});
break;
case 500:
Message.error({
message: "服务器内部有异常!"
});
break;
default:
Message.error({
message: "服务器内部异常!"
});
break;
}
};
handle(error);
} else {
Message.error({
message: "请求资源超时!"
});
}
}
);
};

转载于:https://www.cnblogs.com/haojf/p/10243139.html

你可能感兴趣的:(VUE的axios对Promise的封装和拦截器)