axios封装token 拦截等等
import axios from 'axios';
import $store from '../store/index.js';
let baseUrl = '';
let options = {
lock: true,
text: 'Loading',
spinner: 'el-icon-loading',
background: 'rgba(0,0,0,0.7)'
}
import {
Loading,
Message
} from 'element-ui';
let loading = null;
if (process.env.NODE_ENV == 'development') {
baseUrl = '/api'
}
if (process.env.NODE_ENV == 'production') {
baseUrl = '.......'
}
const instance = axios.create({
baseURL: baseUrl,
timeout: 5000,
responseType: 'json',
withCredentials: false,
headers: {
'content-Type': 'application/json'
}
})
instance.interceptors.request.use(
(config) => {
loading = Loading.service(options);
if (config.data.checkToken) {
if ($store.state.login.loginState) {
config.headers.token = $store.state.login.token;
return config
} else {
Message({
showClose: true,
message: '您还没有登录',
type: 'error',
duration: 1000,
onClose: () => {
router.replace({
name: 'login'
});
}
})
}
} else {
return config
}
},
(error) => {
return Promise.reject(error)
}
)
instance.interceptors.response.use(
(response) => {
let res = response.data;
if (res.errorCode = 20000) {
loading.close();
Message({
showClose: true,
message: '登录超时',
type: 'error',
duration: 1000,
onClose: () => {
router.replace({
name: 'login'
});
}
})
}
if (res.token != null || res.token != undefined) {
config.headers.token = res.token;
let userInfo = window.localStorage.getItem('userInfo');
userInfo = JSON.parse(userInfo);
userInfo.token = res.token;
$store.commit('login', userInfo)
}
loading.close();
return response;
},
(error) => {
return Promise.reject(error)
}
)
export default instance
二次封装
import request from './about.js'
const common = {
method: 'get',
data: {}
}
export default {
http: function(options = {}) {
options.url = options.url;
options.method = options.method || common.method;
options.data = options.data || common.data;
return request({
...options
}).then(res => res.data)
},
get: function(url, data = {}, options = {}) {
options.url = url;
options.data = data;
options.method = 'get';
return this.http(options)
},
post: function(url, data = {}, options = {}) {
options.url = url;
options.data = data;
options.method = 'post';
return this.http(options)
},
put: function(url, data = {}, options = {}) {
options.url = url;
options.data = data;
options.method = 'put';
return this.http(options)
},
patch: function(url, data = {}, options = {}) {
options.url = url;
options.data = data;
options.method = 'patch';
return this.http(options)
}
}