axios封装
import axios from 'axios'
import { Message } from 'element-ui'
import { getToken } from '@/utils/auth'
import router from '@/router/index'
import store from '@/store'
axios.defaults.timeout = 50000
axios.defaults.headers.common['Content-Type'] = 'application/json;charset=UTF-8'
axios.interceptors.response.use(
response => {
return response
},
error => {
return Promise.resolve(error.response)
}
)
export default function http (url, data = {}, requirtType = 'POST', config = {}) {
const type = requirtType.toUpperCase()
if (getToken()) axios.defaults.headers.token = `${getToken()}`
return new Promise((resolve, reject) => {
let promise
if (type === 'GET') {
promise = axios.get(url, {
params: data
})
} else if (type === 'DELETE') {
promise = axios.delete(url, {
data: data
})
} else if (type === 'PUT') {
promise = axios.put(url, data)
} else if (type === 'POST') {
promise = axios.post(url, data, config)
}
promise.then(response => {
return checkStatus(response, resolve)
}).then(response => {
if (response.data.code === 0) {
resolve(response.data.data || response.data.code)
} else if (response.data.code === 40001) {
Message({
message: response.data.msg,
type: 'error'
})
resolve(response.data.data || response.data.code)
} else if (response.data.code === 30001) {
Message({
message: response.data.msg,
type: 'error'
})
store.dispatch('login/resetToken')
router.push(`/login`)
} else if (response.data.code === 80001) {
resolve(response.data)
Message({
message: response.data.msg,
type: 'warning'
})
}
}).catch(error => {
console.log(error, 'error')
Message.error(error || '请求数据异常')
})
})
}
function checkStatus (response, resolve) {
console.log(response, '-------')
if (response && (response.status === 200 || response.status === 304 || response.status === 400)) {
return response
} else if (response && (response.status === 500)) {
console.log(500)
resolve(500)
}
}