环境的切换

  1. if (process.env.NODE_ENV == 'development') {
  2. axios.defaults.baseURL = 'https://www.baidu.com';}
  3. else if (process.env.NODE_ENV == 'debug') {
  4. axios.defaults.baseURL = 'https://www.ceshi.com';
  5. }
  6. else if (process.env.NODE_ENV == 'production') {
  7. axios.defaults.baseURL = 'https://www.production.com';
  8. }

创建axios实例

  1. const service = axios.create({
  2. baseURL:baseURL//api
  3. timeout:30000 //请求超时时间
  4. })

requset请求拦截器

  1. service.interceptors.request.use(
  2. config=>{
  3. if(localStorage.getItem('token')&&localStorage.getItem('id')){
  4. config.headers.Authorization='Bearer '+localStorage.getItem('token')
  5. }
  6. return config
  7. },error=>Promise.reject(error)
  8. )

response 响应拦截器

  1. service.intercepors.response.use(
  2. response=>{
  3. response
  4. },error=>{
  5. if(error.response.status==401||error.response.status==402){
  6. router.push('/login')
  7. }
  8. return Promise.reject(error)
  9. }
  10. )

暴露出

  1. export default service

参考文献

https://www.jianshu.com/p/a38cba9bba96