axios RESTful 接口封装....(进一步优化版本)

import axios from 'axios'
import { baseUrl, localUrl } from '@/config/env'
import Vue from 'vue'
import vuex from 'vuex'
import store from '../store'
const instance = axios.create()
instance.defaults.baseURL = baseUrl
instance.interceptors.request.use(
function(config) {
if (Lockr.get('token')) {
config.headers.common['Authorization'] = Lockr.get('token')
}
return config
},
error => {
return Promise.reject(error)
}
)
instance.interceptors.response.use(
res => {
if (res.data.code) {
switch (res.data.code) {
case 401:
Lockr.rm('token')
window.location.href="/#/benjo/mphjo/"
break
}
} else {
}
return res
},
err => {
if (err && err.response) {
switch (err.response.status) {
case 400:
err.message = '请求错误'
break
case 401:
err.message = '授权失败,请检查token'
break
case 403:
err.message = '拒绝访问'
break
case 404:
err.message = `请求${err.response.config.url
.split('/')
.pop()
.replace(/\.html/, '')}接口出错`
break
case 408:
err.message = '请求超时'
break
case 500:
err.message = '万博manbetx手机在线登录网址内部错误'
break
case 501:
err.message = '服务未实现'
break
case 502:
err.message = '网关错误'
break
case 503:
err.message = '服务不可用'
break
case 504:
err.message = '网关超时'
break
case 505:
err.message = 'HTTP版本不受支持'
break
default:
}
}
store.commit('setModal', err.message)
return Promise.reject(err)
}
)
export function ajax(url, params, type) {
let config = { method: type || 'post' }
if (type === 'get') {
config.params = params
} else if (type === 'put' || type === 'patch' || type === 'delete') {
config.data = type ? {} : params
config.headers = { 'Content-Type': 'application/x-www-form-urlencoded' }
config.transformRequest = [
() => {
let ret = new URLSearchParams()
for (let key in params) {
ret.append(key, params[key])
}
return ret
}
]
} else {
config.data = type ? {} : params
config.headers = { 'Content-Type': 'multipart/form-data' }
config.transformRequest = [
() => {
if (!_.isPlainObject(params)) {
if (params instanceof FormData) {
return params
} else {
let ret = new FormData(params)
return ret
}
} else {
let ret = new FormData()
for (var key in params) {
ret.append(key, params[key])
}
return ret
}
}
]
}
return instance(url, config).then(response => {
return response.data
})
}

0 个评论

要回复文章请先登录注册