fetch-api.js 6.83 KB
import axios from 'axios';
import { Message, MessageBox } from 'element-ui'
import store from '../store'
import { getToken } from '@/utils/auth'
// import {
//   Toast
// } from 'vant';

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

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

// 服务器地址

let requestDomain = "https://ow.go.qudone.com";
if (location.href.indexOf("://k.wxpai.cn") > 0 || location.href.indexOf("://h5.k.wxpai.cn") > 0) {
  requestDomain = "https://api.k.wxpai.cn/bizproxy";
}

/**
 * header不加session的白名单
 */
let headerWhiteList = [
  "kdapi/file/upload"
]

// request拦截器
/*axios.interceptors.request.use(
  config => {
    let addSession = true;
    for (let index = 0; index < headerWhiteList.length; index++) {
      if (config.url.indexOf(headerWhiteList[index]) > -1) {
        addSession = false;
        break;
      }
    }
    if (addSession) {
      //config.headers['adminSessionId'] = getToken() // 让每个请求携带自定义token 请根据实际情况自行修改
    }
    return config
  },
  error => {
    // Do something with request error
    console.log(error) // for debug
    Promise.reject(error)
  }
)*/
// 响应拦截器
axios.interceptors.response.use(
  response => {
    let res = response.data;
    console.log(res);
    if (response.data.code === 200) {
      return Promise.resolve(response.data);
    } else {
      if (res.code == 404) {
        store.dispatch('FedLogOut').then(() => {
          location.reload() // 为了重新实例化vue-router对象 避免bug
        })
      } else {
        if (res.errMsg) {
          Message({
            message: res.errMsg,
            type: 'error',
            duration: 5 * 1000
          })
        }
        return Promise.resolve(response.data);
      }
    }
  },
  error => {
    return Promise.reject(error);
  }
);

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

/**
 * 封装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 = (url, data) => {
  return axios.post(`${requestDomain}${url}`, data, formDataHeaders).then(res => res);
}


/*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*!/
};*/

export const request = {

  post(url, data) {
    //return axios.post(`${requestDomain}${url}`, data);
    let requestUrl = url.indexOf('://') >= 0 ? `${url}` : `${requestDomain}${url}`
    return axios.post(requestUrl, data)
  },
  get(url, data) {
    //return axios.get(`${requestDomain}${url}`, { params: data });
    let requestUrl = url.indexOf('://') >= 0 ? `${url}` : `${requestDomain}${url}`
    return axios.get(requestUrl, {
      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*/
  postTest(url, data) {
    axios({ // 用axios发送post请求
      method: 'post',
      url: `${requestDomain}${url}`, // 请求地址
      data: data, // 参数
      responseType: 'blob' // 表明返回服务器返回的数据类型
    }).then(res => { // 处理返回的文件流
      console.log('请求头:', res.headers)
      console.log('res的数据:', res)
      const filename = res.headers['content-disposition'].split('=')[1]
      console.log('文件名:', filename)
      const blob = new Blob([res.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })//new Blob([res])中不加data就会返回下图中[objece objece]内容(少取一层)
      const elink = document.createElement('a')
      elink.download = filename
      elink.style.display = 'none'
      elink.href = URL.createObjectURL(blob)
      document.body.appendChild(elink)
      elink.click()
      document.body.removeChild(elink)
      URL.revokeObjectURL(elink.href) // 释放URL 对象

    })

    var xhr = new XMLHttpRequest()
    //xhr.open("POST", "https://ow.go.qudone.com/zlzmapi/admin/member/export/test", true);
    xhr.open('POST', 'http://127.0.0.1:8011/zlzmapi/admin/member/export/test', true)
    xhr.setRequestHeader('adminSessionId', 'a91986990ed049bebd0b4ab67d346229')
    xhr.responseType = 'blob'
    xhr.onload = function() {
      if (this.status === 200) {
        //var blob = new Blob([this.response], {type: 'application/vnd.ms-excel;charset=ISO8859-1'});
        var blob = new Blob([this.response], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })
        console.log('打印response:', this)
        var a = document.createElement('a')
        var url = window.URL.createObjectURL(blob)
        a.href = url
        document.body.appendChild(a)
        a.click()
      }
    }
    xhr.send()

    /* return axios.post(`${requestDomain}${url}`, data, formDataHeaders).then(res => {
       let fileName = res.headers['Content-Disposition']
       console.log('文件名:', fileName)
       console.log('res的数据:', res)
       console.log('res的data的数据:', res.data)
       console.log('测试导出2')
       //将文件流转成blob形式
       const blob = new Blob([res.data], { type: 'application/vnd.ms-excel;charset=utf-8' })
       console.log('blob的值:', blob)
       const elink = document.createElement('a')
       elink.style.display = 'none'
       elink.href = URL.createObjectURL(blob)
       document.body.appendChild(elink)
       elink.click()
       URL.revokeObjectURL(elink.href) // 释放URL 对象
       document.body.removeChild(elink)
     /!*  let objectUrl = URL.createObjectURL(blob)
        window.location.href = objectUrl
 *!/
     })*/
  }
}