UNPKG

vue-cli-plugin-winupon

Version:

winpuon vue-cli3 plugin

86 lines (79 loc) 2.22 kB
import Axios from "axios"; // 如果请求话费了超过 `fetchTimeout` 的时间,请求将被中断 const fetchTimeout = 30000; // 跨域请求时是否需要使用凭证(携带cookie时需开启) const withCredentials = false; let defaultHost; // let protocol = window.location.protocol; //协议 // let host = window.location.host; //主机+端口 if (process.env.NODE_ENV === "production") { defaultHost = ""; } else { defaultHost = "/api"; } /* ----------------Axios-------------------- */ const server = Axios.create({ baseURL: defaultHost, timeout: fetchTimeout, withCredentials: withCredentials }); // 添加请求拦截器 server.interceptors.request.use( config => { // 在发送请求之前做些什么 return config; }, error => { // 对请求错误做些什么 return Promise.reject(error); } ); // 添加响应拦截器 server.interceptors.response.use( response => { // 对响应数据做点什么 if (response.status === 200) { // 如果返回是文件二进制流, 提取文件名 返回 二进制流 if (response.headers["content-type"].include("application/data")) { const attachment = response.headers["content-disposition"].split( "filename=" ); const fileName = attachment ? decodeURIComponent(attachment[1]) : ""; response.data = { fileName: fileName, blob: response.data }; } return Promise.resolve(response); } else { return Promise.reject(response); } }, error => { // 对响应错误做点什么 return Promise.reject(error); } ); /** * * @param {String} url 请求地址 * @param {Array} data 请求体 * @param {String} method 请求方法 */ const fetch = (url, data = [], method = "get") => { if (method === "get") { return server({ url: url, method: method, params: data }); } else if (method === "post") { return server({ url: url, method: method, data: data }); } }; const install = Vue => (Vue.prototype.$fetch = fetch); export default { install, fetch };