|
@@ -1,75 +1,4 @@
|
|
|
-import axios from 'axios'
|
|
|
+import apiCreator from './apiCreator'
|
|
|
import Constant from './Constant'
|
|
|
|
|
|
-export class AjaxError extends Error {
|
|
|
- code = 0
|
|
|
-
|
|
|
- constructor (msg, code) {
|
|
|
- super(msg || '未知错误')
|
|
|
- this.code = code
|
|
|
- }
|
|
|
-}
|
|
|
-
|
|
|
-const CancelToken = axios.CancelToken
|
|
|
-
|
|
|
-const link = document.createElement('a')
|
|
|
-
|
|
|
-// const RESPONSE_ERROR = 'ResponseError'
|
|
|
-const REQUEST_CANCEL = 'RequestCancel'
|
|
|
-
|
|
|
-const request = axios.create({
|
|
|
- baseURL: Constant.REQUEST_PREFIX,
|
|
|
- timeout: 300000
|
|
|
-})
|
|
|
-
|
|
|
-request.interceptors.request.use(config => {
|
|
|
- return config
|
|
|
-}, error => new Promise((resolve, reject) => reject(error)))
|
|
|
-
|
|
|
-request.interceptors.response.use(response => new Promise((resolve, reject) => {
|
|
|
- const { config, data } = response
|
|
|
- if (/^(blob)$/i.test(config.responseType)) {
|
|
|
- if (data instanceof Blob) {
|
|
|
- const match = /filename=([^;]+)/.exec(response.headers['content-disposition'])
|
|
|
- if (match) {
|
|
|
- let filename = decodeURIComponent(match).split(',')
|
|
|
- link.href = URL.createObjectURL(data)
|
|
|
- link.download = filename ? filename[filename.length - 1] : ''
|
|
|
- link.click()
|
|
|
- URL.revokeObjectURL(link.href)
|
|
|
- }
|
|
|
- return resolve(response)
|
|
|
- }
|
|
|
-
|
|
|
- return resolve(data)
|
|
|
- }
|
|
|
-
|
|
|
- if (typeof data !== 'object' || data === null) {
|
|
|
- return reject(new AjaxError('数据格式不正确', 30000))
|
|
|
- }
|
|
|
-
|
|
|
- const { type } = data
|
|
|
- if (type === 'success') {
|
|
|
- return resolve(data.data)
|
|
|
- }
|
|
|
-
|
|
|
- return reject(new AjaxError(data.msg, 500))
|
|
|
-}), error => {
|
|
|
- if (error.message === REQUEST_CANCEL) {
|
|
|
- return
|
|
|
- }
|
|
|
-
|
|
|
- if (!(error instanceof AjaxError)) {
|
|
|
- error = new AjaxError('服务器正忙', 500)
|
|
|
- }
|
|
|
-
|
|
|
- return Promise.reject(error)
|
|
|
-})
|
|
|
-
|
|
|
-export const api = (config) => {
|
|
|
- const source = CancelToken.source()
|
|
|
- config = Object.assign({ cancelToken: source.token }, config)
|
|
|
- const promise = request(config)
|
|
|
- promise.abort = () => source.cancel(REQUEST_CANCEL)
|
|
|
- return promise
|
|
|
-}
|
|
|
+export const api = apiCreator(Constant.REQUEST_PREFIX)
|