vue3 typescript axios拦截器
vue3 typescript axios拦截器
·
封装request
// src/utils/request.ts
import axios, { AxiosResponse, InternalAxiosRequestConfig } from "axios"
import { ElMessage } from "element-plus"
import { getToken, removeToken } from "@/utils/auth"
//创建axios实例对象,添加全局配置
const service = axios.create({
baseURL: '/api',
timeout: 8000,
})
//请求拦截
service.interceptors.request.use((config: InternalAxiosRequestConfig): InternalAxiosRequestConfig<any> => {
if (getToken()) {
config.headers["Authorization"] = "Bearer " + getToken()
}
if (config.headers["Content-Type"] == "application/x-www-form-urlencoded") {
config.data = JSON.stringify(config.data)
}
return config
})
// 响应拦截
service.interceptors.response.use(
(response: AxiosResponse) => {
const { data, status, statusText, config } = response
if (status !== 200 || data.code !== 200) {
if (data.code === 401) {
// 未登陆
ElMessage.error("未登陆")
removeToken()
location.reload()
}
ElMessage.error(data.message)
return Promise.reject(data.message)
}
// 直接返回后端data的数据,后端数据格式{code:200, message:"", data: []}
return data
},
(error) => {
ElMessage.error("网络异常,请稍候再试")
// 在响应错误的时候的逻辑处理
return Promise.reject(error)
}
)
export default service
使用拦截器
import request from "@/utils/request"
request.get(url[, config])
request.delete(url[, config])
request.head(url[, config])
request.options(url[, config])
request.post(url[, data[, config]])
request.put(url[, data[, config]])
request.patch(url[, data[, config]])
更多推荐
已为社区贡献1条内容
所有评论(0)