1、直接贴代码:
为了更方便研究,建议复制到自己的代码编辑器中
import axios from 'axios'
import { Message, Loading } from 'element-ui'
import { getToken, getUserId, removeToken } from '@/utils/auth'
import { BASE_URL } from '@/utils/requestConfig'
// create an axios instance
const request = axios.create({
baseURL: BASE_URL, // url = base url + request url
timeout: 20 * 1000 // request timeout
})
function getPromiseFunc(url, params, headers, config) {
return new Promise((resolve, reject) => {
request.get(url, { params, headers, ...config }).then((res) => {
if (res.status === 200) {
resolve(res)
} else {
reject(res.msg)
}
}).catch((err) => {
reject(err)
})
})
}
function postPromiseFunc(url, params, headers, config) {
return new Promise((resolve, reject) => {
request.post(url, params, { headers, ...config }).then((res) => {
if (res.status === 200) {
resolve(res)
} else {
reject(res.msg)
}
}).catch((err) => {
reject(err)
})
})
}
const get = function(url, params, type, config) {
const headers = {
}
if (type === 'blob') {
getPromiseFunc(url, params, { ContentType: 'application/vnd.ms-excel', responseType: 'blob', ...config })
} else {
headers['Content-Type'] = 'application/json'
getPromiseFunc(url, params, headers, config)
}
}
const post = function(url, params, type = 1, config = '') {
if (type === 1) {
const formData = new FormData()
for (const key in params) {
if (params[key] === 'null') {
formData.append(key, null)
} else if (params[key] !== null) {
formData.append(key, params[key])
}
}
return postPromiseFunc(url, formData, { 'Content-Type': 'multipart/form-data' }, config)
} else if (type === 2) {
const formData = new FormData()
for (const key in params) {
if (params[key] === 'null') {
formData.append(key, null)
} else if (params[key] !== null) {
formData.append(key, params[key])
}
}
return postPromiseFunc(url, formData, { 'Content-Type': 'multipart/form-data' }, config)
} else if (type === 'blob') {
const formData = new FormData()
for (const key in params) {
if (params[key] === 'null') {
formData.append(key, null)
} else if (params[key] !== null) {
formData.append(key, params[key])
}
}
return postPromiseFunc(url, formData, { 'Content-Type': 'application/vnd.ms-excel' }, { ...config, 'responseType': 'blob' })
} else {
let paramsObj
if (typeof params === 'object') {
paramsObj = {}
for (const key in params) {
if (params[key] === 'null') {
paramsObj[key] = null
} else if (params[key] !== null) {
paramsObj[key] = params[key]
}
}
} else {
paramsObj = params
}
return postPromiseFunc(url, paramsObj, { 'Content-Type': 'application/json' }, config)
}
}
let load
// request interceptor
request.interceptors.request.use(
config => {
// do something before request is sent
// token赋值
config.headers['token'] = getToken()
config.headers['userId'] = getUserId()
load = Loading.service({
lock: true,
text: '正在加载中...',
spinner: 'el-icon-loading',
background: 'rgba(0, 0, 0, 0.1)'
})
return config
},
error => {
// 请求错误回调函数
console.log(error) // for debug
return Promise.reject(error)
}
)
// response interceptor
request.interceptors.response.use(
/**
* If you want to get http information such as headers or status
* Please return response => response
*/
/**
* Determine the request status by custom code
* Here is just an example
* You can also judge the status by HTTP Status Code
*/
response => {
if (load) {
load.close()
load = ''
}
const res = response.data
if (response.request.responseType === 'blob') {
return response
}
if (res.status === 401) {
removeToken()
localStorage.clear()
Message({
message: res.msg,
type: 'error',
duration: 5 * 1000
})
location.reload()
} else if (res.status !== 200) {
Message({
message: res.msg || '',
type: 'error',
duration: 5 * 1000
})
return Promise.reject(new Error(res.msg || '请求服务器错误'))
} else {
return res
}
},
error => {
if (load) {
load.close()
load = ''
}
if (error.message.indexOf('timeout of') > -1) {
error.message = '请求超时,请重新进行相关操作'
}
console.log('err' + error) // for debug
Message({
message: error.message,
type: 'error',
duration: 5 * 1000
})
return Promise.reject(error)
}
)
export { request, get, post }