vue项目 axios封装第二弹
import axios from "axios"; import qs from "qs"; import { Message, MessageBox } from "element-ui"; // 创建axios实例 const service = axios.create({ withCredentials: true, // baseURL: '/api', // api的base_url timeout: 10000 // 请求超时时间 }); // request拦截器 service.interceptors.request.use( config => { config.data && (config.data = qs.stringify(config.data)); // 请求头部带上token localStorage.getItem("mskj_token") && (config.headers.Authorization = `token ${localStorage.getItem( "mskj_token" )}`); return config; }, error => { return Promise.reject(error); } ); // respone拦截器 service.interceptors.response.use( response => { // 如果code不存在则返回正确数据 code存在则是各种失败状态 if (!response.data.code || response.data.code == 200) { return response; } else { // code存在 错误提示 if (response.data.code == 401) { MessageBox.confirm("你已离线", "确定登出", { confirmButtonText: "重新登录", cancelButtonText: "取消", type: "warning" }).then(() => { localStorage.removeItem("mskj_token"); location.reload(); // 重新实例化vue-router对象 避免bug }); } else if (response.data.code == 400) { // 登录失败 Message.error("账号或密码错误"); return false; } else { Message.error( `发生了错误:${response.data.code} - ${ response.data.message }` ); return false; } } }, error => { Message({ message: `发生了错误:${error.response.status} - ${error.response.statusText}`, type: "error", duration: 1.5 * 1000 }); return Promise.reject(error.response); // 返回接口返回的错误信息 } ); export default service;
使用
import axios from "common/js/http"; import { globalApi } from "common/global"; // 登录 export function login(data) { return axios.post(`${globalApi}/user/login`, data).then(res => { return Promise.resolve(res); }); }