fetch-api.js 5.83 KB
import axios from 'axios';
import Vue from 'vue';
import Router from '../router'

// import {
//   Toast
// } from 'vant';

function Toast(msg) {
  console.log("msg:", msg);
}

// axios的默认url
// axios.defaults.baseURL = ""

// 服务器地址
let base = "https://ow.go.qudone.com";
let baseWxAppid = "wx9fc8816188c0ef2a";
let wxOauthUrl = "http://clubwxuat.hm.liby.com.cn/api/getOpenId.htm";
if (location.href.indexOf("//k.wxpai.cn") > 0) {
  base = "https://api.k.wxpai.cn/bizproxy"
  baseWxAppid = "wx9fc8816188c0ef2a";
  wxOauthUrl = "http://clubwxuat.hm.liby.com.cn/api/getOpenId.htm";
}

let whileList = [
  "https://api.k.wxpai.cn/bizproxy/kdapi/file/upload"
]
// let base = COM.baseUrl;

// 请求拦截器
axios.interceptors.request.use(
  config => {
    // 每次发送请求之前判断是否存在token,如果存在,则统一在http请求的header都加上token,不用每次请求都手动添加了
    // 即使本地存在token,也有可能token是过期的,所以在响应拦截器中要对返回状态进行判断
    const token = store.getSession();
    if (token && whileList.indexOf(config.url) < 0) {
      config.headers["sessionId"] = token;
    }
    return config;
  },
  error => {
    return Promise.error(error);
  })

// 响应拦截器
axios.interceptors.response.use(
  response => {
    if (response.status === 200) {
      if (response.data.code === 200) {
        return Promise.resolve(response);
      } else {
        if (response.data.code == 404) {
          store.removeSession();
          store.saveRedirectUrl();
          Router.push("/");
        }
        return Promise.reject(response);
      }
    } else {
      return Promise.reject(response);
    }
  },
  // 服务器状态码不是200的情况
  error => {
    console.log("Router.path === ", Router.history.current);
    if (error.response.status) {
      switch (error.response.status) {
        case 404:
          Toast({
            message: '网络请求不存在',
            duration: 1500,
            forbidClick: true
          });
          break;
        // 其他错误,直接抛出错误提示
        default:
          Toast({
            message: error.response.data.message,
            duration: 1500,
            forbidClick: true
          });
      }
      return Promise.reject(error.response);
    }
  }
);

//formDataHeaders设置
let formDataHeaders = {
  headers: {
    "Content-Type": "multipart/form-data"
  }
}

/**
 * 封装get方法
 * @param {*} params
 */
export const httpGet = params => {
  let {
    url,
    data
  } = params;
  data = !data ? {} : data;
  let requestUrl = url.indexOf("http:") >= 0 || url.indexOf("https:") >= 0 ? url : `${base}${url}`;
  return axios.get(requestUrl, {
    params: data
  }).then(res => res.data.content);
}

/**
 * 封装post方法
 * @param {*} params
 */
export const httpPost = params => {
  let {
    url,
    data
  } = params;
  let requestUrl = url.indexOf("http:") >= 0 || url.indexOf("https:") >= 0 ? url : `${base}${url}`;
  return axios.post(requestUrl, data).then(res => res.data.content);
}

export const store = {
  putSession: function (sessionId) {
    localStorage.setItem("_jiajia_childrenhost_sesson", sessionId);
  },
  getSession: function () {
    return localStorage.getItem("_jiajia_childrenhost_sesson");
  },
  removeSession: function () {
    localStorage.removeItem("_jiajia_childrenhost_sesson");
  },
  saveRedirectUrl() {
    let current = Router.history.current || {};
    let data = {
      route: current.path,
      params: current.query
    }
    localStorage.setItem("_jiajia_childrenhost_redirect", JSON.stringify(data));
  },
  getRedirectUrl() {
    let dataStr = localStorage.getItem("_jiajia_childrenhost_redirect");
    if (dataStr) {
      let data = JSON.parse(dataStr);
      let path = data.route;
      let sep = "?";
      if (data.params) {
        for (let key in data.params) {
          path += sep + key + "=" + data.params[key];
          sep = "&";
        }
      }
      return path;
    }
    return null;
  },
  delRedirectUrl() {
    localStorage.removeItem("_jiajia_childrenhost_redirect");
  },
  getWxAppId() {
    return `${baseWxAppid}`;
  },
  toWxLogin() {
    let baseUrl = location.origin + location.pathname;
    let returnUrl = encodeURIComponent(`${wxOauthUrl}` + "?returnUrl=" + baseUrl + "?openId=OPENID&p=p");
    let oauthUrl = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + `${baseWxAppid}` + "&redirect_uri=" + returnUrl + "&response_type=code&scope=snsapi_userinfo&stats=" + new Date().getTime() + "#wechat_redirect";
    location.href = oauthUrl;
  }
}

/**
 * 封装post方法
 * @param {*} params
 * data数据是 formdata格式
 * 例如:
 *          this.file = file
            let data = new FormData() //使用formData对象
            data.append('path', '/pro/mzczcradmin/')
            data.append('file', file.file)
 */
export const formdata = params => {
  let {
    url,
    data
  } = params;
  let requestUrl = url.indexOf("http:") >= 0 || url.indexOf("https:") >= 0 ? url : `${base}${url}`;
  return axios.post(requestUrl, data, formDataHeaders).then(res => res.data);
}


export const request = {
  post(url, data) {
    return axios.post(`${requestDomain}${url}`, data);
  },
  get(url, data) {
    return axios.get(`${requestDomain}${url}`, { params: data });
  },
  form(url, params) {
    let formData = new FormData(); //使用formData对象
    for (let key in params) {
      formData.append(key, params[key]);
    }
    let requestUrl = url.indexOf("://") >= 0 ? `${url}` : `${requestDomain}${url}`;
    return axios.post(requestUrl, formData, formDataHeaders)
  },
  build(url, params){
    let fullUrl = `${requestDomain}${url}`;
    let split = "";
    for(let key in params){
      if(split){
        split = "&";
      } else {
        split = "?"
      }
      fullUrl += split + key +"="+params[key];
    }
    return fullUrl;
  },
  /*test*/
};