// 环境变量let env = process.env.NODE_ENV;env = \'production\';// development开发 production生产let baseUrl = \'\';if (env === \'development\') {baseUrl = \'http://localhost:3011\';} else {baseUrl = \'http://huruqing.cn:3011\';}// 创建axios实例const service = axios.create({// api 的 base_urlbaseURL: baseUrl,timeout: 50000, // 请求超时时间(因为需要调试后台,所以设置得比较大)});// request拦截器(请求前的处理)service.interceptors.request.use(config => {let token = localStorage.getItem(\'token\');if (token) {config.headers[\'user-token\'] = token; // 让每个请求携带自定义token 请根据实际情况自行修改}return config;},error => {// Do something with request errorconsole.log(error); // for debugreturn Promise.reject(error);},);// response 拦截器(数据返回后的处理)service.interceptors.response.use(response => {const res = response.data;if (res.code == 666) {return response.data;} else if (res.code == 603) {// 跳转到登陆页面} else {return Promise.reject(\'error\');}},error => {console.log(\'err\' + error); // for debugreturn Promise.reject(error);},);const get = (url, data) => {return service.get(url, {params: data,});};const post = (url, data) => {return service.post(url, data);};export default {get,post,};
axios拦截器——Demo
未经允许不得转载:爱站程序员基地 » axios拦截器——Demo