环境的切换
if (process.env.NODE_ENV == 'development') {
axios.defaults.baseURL = 'https://www.baidu.com';}
else if (process.env.NODE_ENV == 'debug') {
axios.defaults.baseURL = 'https://www.ceshi.com';
}
else if (process.env.NODE_ENV == 'production') {
axios.defaults.baseURL = 'https://www.production.com';
}
创建axios实例
const service = axios.create({
baseURL:baseURL//api
timeout:30000 //请求超时时间
})
requset请求拦截器
service.interceptors.request.use(
config=>{
if(localStorage.getItem('token')&&localStorage.getItem('id')){
config.headers.Authorization='Bearer '+localStorage.getItem('token')
}
return config
},error=>Promise.reject(error)
)
response 响应拦截器
service.intercepors.response.use(
response=>{
response
},error=>{
if(error.response.status==401||error.response.status==402){
router.push('/login')
}
return Promise.reject(error)
}
)
暴露出
export default service
参考文献