vue項目對axios的全局配置


一、axios.js文件中
1.//axios 默認配置
axios.defaults.timeout = 50000;   // 超時時間
axios.defaults.baseURL = constant.OA_URL;     // 默認地址
axios.defaults.responseType = 'json';    //類型動態設置
 
2.//整理數據
axios.defaults.transformRequest = function (data) {
//data = Qs.stringify(data);
data = JSON.stringify(data);
  return data;
};

3.// 路由請求攔截
// http request 攔截器
axios.interceptors.request.use(
  config => {
    //config.data = JSON.stringify(config.data);  
    config.headers[‘Content-Type‘] = ‘application/json;charset=UTF-8‘;
    //判斷是否存在ticket,如果存在的話,則每個http header都加上ticket
    if (cookie.get("token")) {
        //用戶每次操作,都將cookie設置成2小時
        cookie.set("token",cookie.get("token") ,1/12)    
        cookie.set("name",cookie.get("name") ,1/12)
     config.headers.token = cookie.get("token");
     config.headers.name= cookie.get("name");
    }
    
    return config;
  },
  error => {
    return Promise.reject(error.response);
  });

4.// 路由響應攔截
// http response 攔截器
axios.interceptors.response.use(
  response => {
    if (response.data.resultCode=="404") {
        console.log("response.data.resultCode是404")
        // 返回 錯誤代碼-1 清除ticket信息並跳轉到登錄頁面
//      cookie.del("ticket")
//      window.location.href=‘http://login.com‘
        return
    }else{
        return response;
    }
  },
  error => {
    return Promise.reject(error.response)   // 返回接口返回的錯誤信息
  });
export default axios;


二、在mian.js文件中

import axios from './axios/axios'
Vue.prototype.axios = axios;



免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM