/**
* 资源获取帮助类,需求:
* 1. 常用请求方法
* 2. 自动发送请求头
* 3. 根据状态码进行刷新 token
* 4. 刷新 token 后自动请求上次请求内容
* 5. refresh token 过期时提示登录
* 6. 请求方法返回: 状态码 无论 500 还是 0 都会返回 API 内容, token 过期刷新失败直接返回 false
*/
import storage from './storage.js'
import api from './api.js'
var http = {
$http: {},
config ($http) {
this.$http = $http
},
http (url, data, options, method) {
return this.$http({url: url, method: method, data: data, options: this.autoHeaders(options)}).then((res) => {
let body = res.data
let status = body.status.code
if (status === 401) {
return this.refresh().then((res) => {
if (res) return this.http(url, data, options, method)
return false
})
}
return body
})
},
get (url, data, options) {
return this.http(url, data, options, 'GET')
},
post (url, data, options) {
return this.http(url, data, options, 'POST')
},
delete (url, data, options) {
return this.http(url, data, options, 'DELETE')
},
put (url, data, options) {
return this.http(url, data, options, 'PUT')
},
refresh () {
this.$
http.post(api.refresh, null, this.autoHeaders()).then((res) => {
if (res.data.status.code === 0) {
this.storage.setItem('token', res.data.data.token)
return true
}
return false
})
},
autoHeaders (options = {}) {
return Object.assign({}, {
headers: {
Authorization: `Bearer ${storage.getItem('token')}`
}
}, options)
}
}
export default http
这么写可以吗? 有哪些糟点?