123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140 |
- /*
- * @Author: Rindy
- * @Date: 2021-04-25 15:58:21
- * @LastEditors: Rindy
- * @LastEditTime: 2021-05-08 15:49:54
- * @Description: 注释
- */
- import axios from 'axios'
- // TextDecoder polyfills for lower browser
- if (undefined === window.TextEncoder) {
- window.TextEncoder = class _TextEncoder {
- encode(s) {
- return unescape(encodeURIComponent(s))
- .split('')
- .map(function(val) {
- return val.charCodeAt()
- })
- }
- }
- window.TextDecoder = class _TextDecoder {
- decode(code_arr) {
- return decodeURIComponent(escape(String.fromCharCode.apply(null, code_arr)))
- }
- }
- }
- const fetch = axios.create()
- fetch.interceptors.request.use(
- config => {
- config.headers['token'] = 123
- return config
- },
- error => {
- return Promise.reject(error)
- }
- )
- fetch.interceptors.response.use(
- response => {
- // 正常的文件流
- if (!/json/gi.test(response.headers['content-type'])) {
- return response.data
- }
- // 以文件流方式请求但是返回json,需要解析为JSON对象
- if (response.request.responseType === 'arraybuffer') {
- let enc = new TextDecoder('utf-8')
- let res = JSON.parse(enc.decode(new Uint8Array(response.data)))
- return res
- }
- return response.data
- },
- error => {
- console.error(error)
- }
- )
- const http = {
- retry(func, retries = 0, delay = 1000) {
- return new Promise((resolve, reject) => {
- func()
- .then(resolve)
- .catch(error => {
- if (retries <= 1) {
- reject(error)
- } else {
- setTimeout(() => {
- http.retry(func, retries - 1, delay)
- .then(resolve)
- .catch(reject)
- }, delay)
- }
- })
- })
- },
- get(url) {
- return fetch.get(url)
- },
- getImage(url, retries = 3) {
- return http.retry(
- () =>
- new Promise((resolve, reject) => {
- let img = new Image()
- img.src = url
- img.crossOrigin = 'anonymous'
- img.onload = function() {
- resolve(img)
- }
- img.onerror = function() {
- reject(`[${url}] load fail`)
- }
- }),
- retries
- )
- },
- getBueffer(url) {
- return fetch.get(url, {
- responseType: 'arraybuffer'
- })
- },
- getBlob(url) {
- return fetch.get(url, {
- responseType: 'blob'
- })
- },
- post(url, data) {
- return fetch.post(url, data)
- },
- postFile(url, data) {
- const form = new FormData()
- let cb = null
- if (data.onUploadProgress) {
- cb = data.onUploadProgress
- delete data.onUploadProgress
- }
- for (let key in data) {
- // if (key === 'files' && data[key].length > 0) {
- // for (let i = 0; i < data[key].length; i++) {
- // form.append(key, data[key][i])
- // }
- // } else {
- // form.append(key, data[key])
- // }
- form.append(key, data[key])
- }
- return fetch.post(url, form, {
- headers: {
- 'Content-Type': 'multipart/form-data'
- },
- onUploadProgress: cb
- })
- }
- }
- export { http, fetch }
|