封装 vue axios 方法。通过引入 api/模块.js 调用方法与后台对接口,实现页面的渲染

import axios from 'axios'

import store from '@/store/index'

import Vue from 'vue'

import { Toast } from 'vant';

Vue.use(Toast);

const service = axios.create({

baseURL: '', // api 的 base_url process.env.BASE_API

timeout: 13000 // request timeout

})

//请求的拦截

service.interceptors.request.use(

config => {

if (store.state.token) {

config.headers['token'] = store.state.token

} else {

config.headers['token'] = ''

}

return config

},

)

 

service.interceptors.response.use(

response => {

let path=window.location.href.split('#')[1];

localStorage.setItem('path',path);

if(response.data.wx_login){

//重新token存储信息

localStorage.setItem('token', response.data.wx_login.token)

store.commit('setToken', response.data.wx_login.token);

//存储userInfo信息

localStorage.setItem('userInfo',JSON.stringify( response.data.wx_login.data));

if(response.data.errcode != '1000'){

Toast(response.data.errmsg);

}

return response.data

}

else if (response.data.errcode == '1000') {

//重新赋值token

if (response.data.data) {

localStorage.setItem('token', response.data.data.token)

store.commit('setToken', response.data.data.token);

} else {

localStorage.setItem('token', '');

store.commit('setToken', '');

}

return response.data

} else if (response.data.errcode == '-1005') { //重新登录

localStorage.setItem('token', '');

localStorage.setItem('userInfo', '');

// store.commit('setToken', '');

location.href = '#/sign'

return response.data

} else {

Toast(response.data.errmsg)

return response.data

}

}

)

export default service

你可能感兴趣的:(vue学习)