axios在实际项目中的封装
1、axios的封装
js
import axios from 'axios'
import { message } from 'ant-design-vue'
import {
getLocalToken,
removeLocalToken
} from '@/utils/auth'
const service = axios.create({
timeout: 300000 // 请求超时
})
//请求拦截
service.interceptors.request.use(
(config) => {
const token = getLocalToken() // 获取在本地存储的token
config.headers['Authorization'] = `Bearer ${token}`
config.headers['APPID'] = 'dataValidApp'
return config
},
(error) => {
// 请求错误
return Promise.reject(error)
}
)
// 响应拦截
service.interceptors.response.use(
// 获取响应状态
(response) => {
const res = response.data
if (res.code == 401) {
removeToken()
removeLocalToken()
message.error(res.message || 'Error')
const host = location.host
const protocol = location.protocol
window.location.href = `${protocol}//${host}/base/#/login`
} else if (res.code != 200) {
message.error(res.message || 'Error')
return Promise.reject(res.message) // 返回接口返回的错误信息
} else {
return res
}
},
(err) => {
if (err && err.response) {
switch (err.response.status) {
case 400:
err.message = '请求错误'
break
case 401:
err.message = '未授权,请登录'
break
case 403:
err.message = '拒绝访问'
break
case 404:
err.message = `请求地址出错: ${err.response.config.url}`
break
case 408:
err.message = '请求超时'
break
case 500:
err.message = '服务器内部错误'
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:
}
}
message.error(err.message || 'Error')
return Promise.reject(err) // 返回接口返回的错误信息
}
)
export default service
2、对于封装的axios的使用
js
import request from '@/utils/request'
export function login(data) {
return request({
url: '/qf-admin/user/login',
method: 'post',
data
})
}
export function getInfo(params) {
return request({
url: '/qf-admin/user/info',
method: 'get',
params
})
}
以上封装可直接粘贴到代码中进行使用