axios封装
1:规范化前后端的数据格式,避免出现较大差距
2:前端统一格式,对错误的数据统一处理,便于前端开发
代码
import Vue from 'vue'
import axios from 'axios'
import {bus} from './bus'
const instance = axios.create({
validateStatus: status => {
if (status > 400) {
console.warn(`HTTP 请求出错 status: ${status}`)
}
return status >= 200 && status <= 505
},
headers: {'X-Requested-With': 'XMLHttpRequest'},
xsrfCookieName: 'data_csrftoken',
xsrfHeaderName: 'X-CSRFToken',
withCredentials: true
})
instance.interceptors.request.use(config => {
if (!/^(https|http)?:\/\//.test(config.url)) {
const prefix = config.url.indexOf('?') === -1 ? '?' : '&'
config.url += prefix + 'isAjax=1'
}
return config
}, error => {
return Promise.reject(error)
})
function getMsg (obj, key, message) {
if (Object.prototype.toString.call(obj) === '[object Array]') {
for (let val of obj) {
getMsg(val, key, message)
}
} else if (Object.prototype.toString.call(obj) === '[object Object]') {
for (let key in obj) {
let cur = obj[key]
getMsg(cur, key, message)
}
} else {
if (key !== '') {
obj = key + ': ' + obj
}
message.push(obj)
}
}
instance.interceptors.response.use(response => {
if (!response.data || typeof response.data === 'string') {
let msg = '接口请求异常,请联系管理员'
console.warn('接口异常,', 'HTTP状态码:', response.status)
if (!response.data) {
console.error(msg)
}
response.data = {
code: response.status,
msg: msg
}
} else if (response.status === 401) {
bus.$emit('show-login-modal')
} else if (response.status > 300) {
console.error('HTTP请求出错,状态码为:', response.status)
console.warn('请求信息:', response)
let msg = response.statusText
if (response.data && response.data.message) {
msg = response.data.message
}
response.data = {
code: response.status,
msg: msg
}
} else {
response.data.msg = ''
}
let messages = []
if (response.data.messages) {
if (Object.prototype.toString.call(response.data.messages) === '[object Object]') {
getMsg(response.data.messages, '', messages)
response.data.msg = messages.join('; ')
} else if (Object.prototype.toString.call(response.data.messages) === '[object Array]') {
response.data.msg = response.data.messages.join(';')
}
} else if (response.data.message) {
response.data.msg = response.data.message
}
if (response.data.code !== 'OK' && response.data.code !== 0) {
if (response.data.code === 'data_SETTING_ERROR') {
bus.$emit('show-data-modal')
}
return Promise.reject(response)
}
return response
}, error => {
return Promise.reject(error)
})
Vue.prototype.$http = instance
export default instance
main.js里面引用ajax.js文件
import ajax from './ajax'
ajax.interceptors.response.use(response => {
return response
}, error => {
if (error.status === 401) {
window.location = window.login_url + '?c_url=' + window.location.href
}
if (error.status === 403) {
bus.$emit('api-error:user-permission-denied')
}
return Promise.reject(error)
})
总结
1:这个axios的封装比较简单,只对code,data,message进行统一的处理。
2:对于拦截请求,请求没有结束跳转路由,一个方法体多次请求,缓存这些问题也可以封装起来处理,这个后期进行添加
3:封装的axios能够有效地对后台数据做一次过滤,能够使前端联调数据更方便