|
/**
|
* 通用的http请求类
|
*/
|
export default class Http {
|
static create(configs = {}) {
|
const defaultConfigs = {
|
apiEnv: 'php',
|
}
|
configs = { ...defaultConfigs, ...configs }
|
return new this(configs)
|
}
|
|
//获取头部提示信息
|
static getHeaderMessage(response) {
|
if (!response) {
|
return ""
|
}
|
return response.headers.has('X-Message') ? unescape(response.headers.get('X-Message').replace(/"/g, '').replace(/\\/g, "%")) : response.statusText
|
}
|
|
//获取GET请求指定查询参数
|
static getQueryParameter(parameter) {
|
const url = window.location.href
|
const queryIndex = url.lastIndexOf('?')
|
const query = queryString.parse(url.substr(queryIndex))
|
return query[parameter] ? query[parameter] : null
|
}
|
|
static getAccessToken() {
|
const tokenParameter = 'access_token'
|
if (Http.getQueryParameter(tokenParameter) !== null) {
|
return Http.getQueryParameter(tokenParameter)
|
}
|
return window.localStorage.getItem('access_token')
|
}
|
|
constructor(configs) {
|
this.configs = configs
|
}
|
|
async request(url, options = {}) {
|
url = this._urlAddQuery(this._urlAddHost(url), options)
|
//options['mode'] = 'no-cors'
|
|
return await fetch(url, options)
|
.then(this._checkStatus)
|
//.catch((e) => {
|
// message.error(e, 3);
|
// return Promise.reject(e)
|
// })
|
}
|
|
get(url, options = {}) {
|
const defaultOptions = {
|
method: 'GET',
|
headers: {
|
'Accept': 'application/json',
|
'Origin': 'http://localhost:8000',
|
},
|
}
|
options = { ...defaultOptions, ...options }
|
return this.request(url, options)
|
}
|
|
post(url, options = {}) {
|
const defaultOptions = {
|
method: 'POST',
|
headers: {
|
'Accept': 'application/json',
|
},
|
}
|
defaultOptions['headers']['Content-Type'] = this._getContentType()
|
|
options = { ...defaultOptions, ...options }
|
if (options.body) {
|
options.body = this._encodeBody(options.headers['Content-Type'], options.body)
|
}
|
|
return this.request(url, options)
|
}
|
|
put(url, options = {}) {
|
const defaultOptions = {
|
method: 'PUT',
|
headers: {
|
'Accept': 'application/json',
|
},
|
}
|
defaultOptions['headers']['Content-Type'] = this._getContentType()
|
|
options = { ...defaultOptions, ...options }
|
if (options.body) {
|
options.body = this._encodeBody(options.headers['Content-Type'], options.body)
|
}
|
|
return this.request(url, options)
|
}
|
|
patch(url, options = {}) {
|
const defaultOptions = {
|
method: 'PATCH',
|
headers: {
|
'Accept': 'application/json',
|
},
|
}
|
defaultOptions['headers']['Content-Type'] = this._getContentType()
|
|
options = { ...defaultOptions, ...options }
|
if (options.body) {
|
options.body = this._encodeBody(options.headers['Content-Type'], options.body)
|
}
|
|
return this.request(url, options)
|
}
|
|
remove(url, options = {}) {
|
const defaultOptions = {
|
method: 'DELETE',
|
headers: {
|
'Accept': 'application/json',
|
},
|
}
|
defaultOptions['headers']['Content-Type'] = this._getContentType()
|
|
options = { ...defaultOptions, ...options }
|
if (options.body) {
|
options.body = this._encodeBody(options.headers['Content-Type'], options.body)
|
}
|
|
return this.request(url, options)
|
}
|
|
downFile(url, options = {}) {
|
let filename = ''
|
let that = this
|
const defaultOptions = {
|
headers: {
|
'Content-Type': this._getContentType(),
|
},
|
}
|
|
options = { ...defaultOptions, ...options }
|
|
if (options.body) {
|
options.body = this._encodeBody(options.headers['Content-Type'], options.body)
|
}
|
return this.request(url, options)
|
.then(function(response) {
|
filename = that._getFileName(response)
|
return response.blob();
|
}).then(function(blob) {
|
FileSaver.saveAs(blob, filename);
|
})
|
}
|
|
_getApiHost() {
|
const apiEnvMap = {
|
php: 'host',
|
java: 'javaHost',
|
javaV1: 'javaHostV1',
|
}
|
const hostName = apiEnvMap[this.configs['apiEnv']] ? apiEnvMap[this.configs['apiEnv']] : 'javaHost'
|
let hostUrl = config.api[hostName]
|
//if (this.configs.port) {
|
// hostUrl += ':' + this.configs.port
|
//}
|
//if (this.configs.secondDir) {
|
// hostUrl += '/' + this.configs.secondDir
|
//}
|
return hostUrl
|
}
|
|
_getAccessToken() {
|
const url = window.location.href
|
const queryIndex = url.lastIndexOf('?')
|
const query = queryString.parse(url.substr(queryIndex))
|
if (query.access_token) {
|
return query.access_token
|
}
|
return window.localStorage.getItem('access_token')
|
}
|
|
_urlAddHost(url) {
|
if (!url.startsWith('http')) {
|
url = this._getApiHost() + url
|
}
|
return url
|
}
|
|
_urlAddQuery(url, options) {
|
if (!options.query) {
|
options.query = {}
|
}
|
options.query.access_token = this._getAccessToken()
|
|
const query = queryString.stringify(options.query)
|
url += (url.includes('?') ? '&' : '?') + query
|
return url
|
}
|
|
_getContentType() {
|
return this.configs['apiEnv'] === 'php' ? 'application/x-www-form-urlencoded' : 'application/json'
|
}
|
|
_encodeBody(type, body) {
|
if (type === 'application/x-www-form-urlencoded') {
|
body = queryString.stringify(body)
|
}
|
else if (type === 'application/json') {
|
body = JSON.stringify(body)
|
}
|
return body
|
}
|
|
_getFileName(response) {
|
var filename = ""
|
var disposition = response.headers.get('Content-Disposition')
|
if (disposition && disposition.indexOf('attachment') !== -1) {
|
var filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/
|
var matches = filenameRegex.exec(disposition)
|
if (matches != null && matches[1]) {
|
filename = matches[1].replace(/['"]/g, '')
|
}
|
}
|
return decodeURI(filename)
|
}
|
|
_checkStatus(response) {
|
if (response.status >= 200 && response.status < 300) {
|
return response
|
}
|
const message = Http.getHeaderMessage(response)
|
//message.error(message, 3);
|
|
//token过期特殊处理
|
if (response.status == 401 && response.headers.has('X-Message') && response.headers.get('X-Message').startsWith("token")) {
|
router.replace('/system/login')
|
const error = new Error("登录已过期请重新登录")
|
throw error
|
}
|
|
const error = new Error(message)
|
error.response = response
|
throw error
|
//return Promise.reject(message)
|
}
|
}
|