Home Article Practice 前端封装axios代码

前端封装axios代码

2023-10-04 01:36  views:477  source:小键人11126656    

import axios from 'axios'
import { useUserStore } from '../stores'
import router from '../router'
import { ElMessage } from 'element-plus'
const baseUrl = ' http://big-event-vue-api-t.itheima.net'
const instance = axios.create({ baseUrl, timeout: 10000 })
// 添加请求拦截器
instance.interceptors.request.use(
function (config) {
// 在发送请求之前做些什么
const useStore = useUserStore()
if (useStore.token) {
config.headers.Authorization = useStore.token
}
return config
},
function (error) {
// 对请求错误做些什么
return Promise.reject(error)
}
)
// 添加响应拦截器
instance.interceptors.response.use(
function (response) {
// 2xx 范围内的状态码都会触发该函数.
// 对响应数据做点什么
if (response.data.code === 0) {
return response
}
ElMessage.error(response.data.message || '服务器异常')
return Promise.reject(response.data)
},
function (error) {
// 超出 2xx 范围的状态码都会触发该函数.
// 对响应错误做点什么
if (error.response?.status === 401) {
router.push('/login')
}
ElMessage.error(error.response.data.message || '服务异常')
return Promise.reject(error)
}
)
export default instance
export { baseUrl }



Disclaimer: The above articles are added by users themselves and are only for typing and communication purposes. They do not represent the views of this website, and this website does not assume any legal responsibility. This statement is hereby made! If there is any infringement of your rights, please contact us promptly to delete it.

字符:    改为:
去打字就可以设置个性皮肤啦!(O ^ ~ ^ O)