import axios from 'axios'
let cancel ,promiseArr = {} const CancelToken = axios.CancelToken; //請求攔截器 axios.interceptors.request.use(config => { //發起請求時,取消掉當前正在進行的相同請求 if (promiseArr[config.url]) { promiseArr[config.url]('操做取消') promiseArr[config.url] = cancel } else { promiseArr[config.url] = cancel } return config }, error => { return Promise.reject(error) }) //響應攔截器 axios.interceptors.response.use(response => { return response }, error => { return Promise.resolve(error.response) }) axios.defaults.baseURL = '/api' //設置默認請求頭 axios.defaults.headers = { 'X-Requested-With': 'XMLHttpRequest' } axios.defaults.timeout = 10000 export default { //get請求 get (url,param) { return new Promise((resolve,reject) => { axios({ method: 'get', url, params: param, cancelToken: new CancelToken(c => { cancel = c }) }).then(res => { resolve(res) }) }) }, //post請求 post (url,param) { return new Promise((resolve,reject) => { axios({ method: 'post', url, data: param, cancelToken: new CancelToken(c => { cancel = c }) }).then(res => { resolve(res) }) }) } }
import axios from 'axios' import {Message,Loading} from 'element-ui' import router from '../router' // 請求攔截 axios.interceptors.request.use(config=> { Loading.service({text:"Loading..."}); return config; }, err=> { Message.error({message: '請求超時!'}); return Promise.resolve(err); }) // 響應攔截 axios.interceptors.response.use(res=> { Loading.service().close(); if (res.data.code == 200) { return res.data.result; } else if (res.data.code == 401) { router.push('/login') } else if(res.data.code == 201){ Message.error({message: res.data.msg}); return Promise.reject(res); } return Promise.reject(res); }, err=> { Loading.service().close(); if (err.response.status == 504||err.response.status == 404) { Message.error({message: '服務器被吃了⊙﹏⊙∥'}); } else if (err.response.status == 403) { Message.error({message: '權限不足,請聯繫管理員!'}); } else { Message.error({message: '未知錯誤'}); } return Promise.reject(err); }) let base = ''; export const postRequest = (url, params) => { return axios({ method: 'post', url: `${base}${url}`, data: params, transformRequest: [function (data) { let ret = '' for (let it in data) { ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&' } return ret }], headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }); } export const getRequest = (url,data='') => { return axios({ method: 'get', params: data, url: `${base}${url}` }); }