1. 程式人生 > >vue 檔案 http配置 跨域問題 俱全

vue 檔案 http配置 跨域問題 俱全

/**
 * http配置
 */
import axios from 'axios'
import qs from 'qs'
import store from '../store/index'
import router from '../router/index'
import {getStore} from 'src/config/cache'

const instance = axios.create();
// axios 配置

//網路連線失敗(連線不上)的時候,延遲5s報錯嗎
instance.defaults.timeout = 120000;
console.log(process.env.NODE_ENV);
if (process.env.NODE_ENV === 'production') {
  //配置生產介面域名
  instance.baseURL = "http://bt-lzxkm.yunzhenshi.com.cn/lzxk/" // 
  // instance.baseURL = "http://192.168.14.32:8082/lzxk/" //   這裡不加 http:// 會有問題 會拼接 192.168.14.32:8082
} else {
  //配置開發介面域名
  instance.baseURL = "http://192.168.18.135:8080/" // 
  // instance.baseURL="http://192.168.18.146:8080/"  // 
  // instance.baseURL="http://192.168.18.142:8080/"  // 


}
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8'

//把 token 放在請求的頭部。
axios.interceptors.request.use = instance.interceptors.request.use
instance.interceptors.request.use(
  config => {
    //在請求攔截器中配置公共引數 sessionId
    //const sessionId = "9999";
    // 如果是post請求就把預設引數拼到data裡面
    // 如果是get請求就拼到params裡面
    let accountNum = '';
    if (getStore('accountNum')) {
      accountNum = getStore('accountNum');
    }

    let accountName = '';
    if (getStore('accountName')) {
      accountName = getStore('accountName');
    }
    if (config.method === 'post') {
      let data = qs.parse(config.data);
      config.data = qs.stringify({
        accountNum: accountNum,
        accountName: accountName,
        ...data
      });
    } else if (config.method === 'get') {
      config.params = {
        accountNum: accountNum,
        ...config.params
      }
    }
    return config
  },
  err => {
    return Promise.reject(err)
  },
)

// http response 攔截器
instance.interceptors.response.use(
  response => {
    if (response.data.code == 12105){
      console.log("返回過期錯誤碼:"+response.data.code);
      alert("登入過期,請重新登入");
      router.currentRoute.path !== 'login' &&
      router.replace({
        path: 'login',
        query: {redirect: router.currentRoute.path},
      });
      return Promise.reject(response.data);
    } else if (response.data.code && response.data.code != 1) {
      alert(response.data.msg);
      return Promise.reject(response.data);
    } else {
      return response
    }


  },
  error => {
    console.log(error);
    if (error.response) {
      switch (error.response.status) {
        case 401:
          // 401 清除token資訊並跳轉到登入頁面
          store.commit(types.LOGOUT)

          // 只有在當前路由不是登入頁面才跳轉
          router.currentRoute.path !== 'login' &&
          router.replace({
            path: 'login',
            query: {redirect: router.currentRoute.path},
          })
      }
    }
    return Promise.reject(error);
//  return Promise.reject(error.response.data)
  },
)

export default instance