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


import { Toast } from "vant";
Vue.use(Toast);

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

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

// 服务器地址
let base = golbal_api_proxy;
let baseWxAppid = global_wx_appid;
let wxOauthUrl = global_wx_oauth_url;


let whileList = [
  "https://api.k.wxpai.cn/bizproxy/kdapi/file/upload",
  "https://api.k.wxpai.cn/bizproxy/kdapi/file/uploadBase64"
]
// 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) {
      return;
    }
    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("/");
        } else {
          Toast(response.data.errMsg);
        }
        return Promise.reject(response);
      }
    } else {
      return Promise.reject(response);
    }
  },
  // 服务器状态码不是200的情况
  error => {
    if (error && error.response && 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() {
    if (!Router.history.current || !Router.history.current.path) {
      return;
    }
    let current = Router.history.current;
    let data = {
      route: current.path == "/" ? "/index" : current.path,
      params: current.query
    }
    localStorage.setItem("_jiajia_childrenhost_redirect", JSON.stringify(data));
  },
  saveWorksRedirectUrl(worksCode) {
    let data = {
      route: "/list",
      params: { worksCode: worksCode }
    };
    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;
      if (!path) {
        return "/index";
      }
      let sep = "?";
      if (data.params) {
        for (let key in data.params) {
          path += sep + key + "=" + data.params[key];
          sep = "&";
        }
      }
      return path;
    }
    return "/index";
  },
  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(`${base}${url}`, data);
  },
  get(url, data) {
    return axios.get(`${base}${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}` : `${base}${url}`;
    return axios.post(requestUrl, formData, formDataHeaders)
  },
  build(url, params) {
    let fullUrl = `${base}${url}`;
    let split = "";
    for (let key in params) {
      if (split) {
        split = "&";
      } else {
        split = "?"
      }
      fullUrl += split + key + "=" + params[key];
    }
    return fullUrl;
  },
  /*test*/
};