import axios from"axios";import{ Message }from"element-ui";import router from"../router";// 创建axios实例const service = axios.create()
service.defaults.baseURL = process.env.VUE_APP_BASE_API
service.defaults.timeout =5000// request拦截器
service.interceptors.request.use((config)=>{// do something before request is sent//添加token请求头if(sessionStorage.getItem("token")){const token = sessionStorage.getItem("token");
config.headers.token = token.replace(/\"/g,"");}return config;},(error)=>{// do something with request error
console.log(error);// for debugreturn Promise.reject(error);});// response interceptor
service.interceptors.response.use(/**
* If you want to get http information such as headers or status
* Please return response => response
*//**
* Determine the request status by custom code
* Here is just an example
* You can also judge the status by HTTP Status Code
*/(response)=>{const res = response;if(res.status ===200&& res.data ===-1){return res.data;},(error)=>{if(error.response){switch(error.response.status){case401:Message({message:"登陆过期,请重新登陆!",type:"error",duration:5*1000});if(process.env.NODE_ENV=="delvelopment"){// 本地开发不进行跳转}elseif(process.env.NODE_ENV=="production"){
router.replace("/login");//上测试和生产记得修改}}}if(
error &&
error.response &&
error.response.data &&
error.response.data.message
){Message({message: error.response.data.message,type:"error",duration:5*1000});}else{Message({message:"后台接口无响应或网络错误!",type:"error",duration:5*1000});}return Promise.reject(error);// 返回接口返回的错误信息});exportdefault service;