mirror of
https://github.com/zuiidea/antd-admin
synced 2026-10-21 23:23:43 +00:00
79 lines
1.8 KiB
JavaScript
79 lines
1.8 KiB
JavaScript
import axios from 'axios'
|
|
import cloneDeep from 'lodash.clonedeep'
|
|
import pathToRegexp from 'path-to-regexp'
|
|
import { message } from 'antd'
|
|
import qs from 'qs'
|
|
|
|
export default function request(options) {
|
|
let { data, url, method = 'get' } = options
|
|
const cloneData = cloneDeep(data)
|
|
|
|
try {
|
|
let domain = ''
|
|
const urlMatch = url.match(/[a-zA-z]+:\/\/[^/]*/)
|
|
if (urlMatch) {
|
|
;[domain] = urlMatch
|
|
url = url.slice(domain.length)
|
|
}
|
|
|
|
const match = pathToRegexp.parse(url)
|
|
url = pathToRegexp.compile(url)(data)
|
|
|
|
for (const item of match) {
|
|
if (item instanceof Object && item.name in cloneData) {
|
|
delete cloneData[item.name]
|
|
}
|
|
}
|
|
url = domain + url
|
|
} catch (e) {
|
|
message.error(e.message)
|
|
}
|
|
|
|
options.url =
|
|
method.toLocaleLowerCase() === 'get'
|
|
? `${url}${cloneData ? '?' : ''}${qs.stringify(cloneData)}`
|
|
: url
|
|
|
|
return axios(options)
|
|
.then(response => {
|
|
const { statusText, status, data } = response
|
|
|
|
let result = {}
|
|
if (typeof data === 'object') {
|
|
result = data
|
|
if (Array.isArray(data)) {
|
|
result.list = data
|
|
}
|
|
} else {
|
|
result.data = data
|
|
}
|
|
|
|
return Promise.resolve({
|
|
success: true,
|
|
message: statusText,
|
|
statusCode: status,
|
|
...result,
|
|
})
|
|
})
|
|
.catch(error => {
|
|
const { response } = error
|
|
let msg
|
|
let statusCode
|
|
if (response && response instanceof Object) {
|
|
const { data, statusText } = response
|
|
statusCode = response.status
|
|
msg = data.message || statusText
|
|
} else {
|
|
statusCode = 600
|
|
msg = error.message || 'Network Error'
|
|
}
|
|
|
|
/* eslint-disable */
|
|
return Promise.reject({
|
|
success: false,
|
|
statusCode,
|
|
message: msg,
|
|
})
|
|
})
|
|
}
|