拦截器
请求拦截器
修改 src/api/request.ts
核心代码:
req.interceptors.request.use(// 拦截配置并更新配置config => {// 获取登录tokenconst token = localStorage.getItem("token")// 使用 JWT Tokenif (token) {config.headers.Authorization = "Bearer " + token}// 将修改后的配置返回return {...config}},// 拦截错误并注入错误信息error => {return Promise.reject(error);}
)
完整代码:
import axios from "axios";// 创建实例
const req = axios.create({baseURL: '/api',timeout: 3000,timeoutErrorMessage: "请求超时,请稍后再试",withCredentials: true, // 跨域headers: {'Content-Type': 'application/json',}
})// 请求拦截器
req.interceptors.request.use(// 拦截配置并更新配置config => {// 获取登录tokenconst token = localStorage.getItem("token")// 使用 JWT Tokenif (token) {config.headers.Authorization = "Bearer " + token}// 将修改后的配置返回return {...config}},// 拦截错误并注入错误信息error => {return Promise.reject(error);}
)// GET 请求
function get(url: string, params: any) {return req.get(url, {params})
}// POST 请求
function post(url: string, data: any) {return req.post(url, data)
}// 导出
export default {req,get,post,
}
响应拦截器
修改 src/api/request.ts
核心代码:
req.interceptors.response.use(// 拦截正常响应response=>{// 获取服务端响应的数据const data = response.data// 响应成功if (data.code===10000 && data.status === true){return data.data}// 响应失败:权限错误if (data.code === 10401 || data.status === 10403 ){message.error(data.msg)localStorage.removeItem("token")location.href="/login"return}// 其他错误message.error(data.msg)return Promise.reject(data)},// 拦截错误响应error => {return Promise.reject(error);}
)
完整代码:
import axios from "axios";
import {message} from "antd";// 创建实例
const req = axios.create({baseURL: '/api',timeout: 3000,timeoutErrorMessage: "请求超时,请稍后再试",withCredentials: true, // 跨域headers: {'Content-Type': 'application/json',}
})// 请求拦截器
req.interceptors.request.use(// 拦截配置并更新配置config => {// 获取登录tokenconst token = localStorage.getItem("token")// 使用 JWT Tokenif (token) {config.headers.Authorization = "Bearer " + token}// 将修改后的配置返回return {...config}},// 拦截错误并注入错误信息error => {return Promise.reject(error);}
)// 响应拦截器
req.interceptors.response.use(// 拦截正常响应response=>{// 获取服务端响应的数据const data = response.data// 响应成功if (data.code===10000 && data.status === true){return data.data}// 响应失败:权限错误if (data.code === 10401 || data.status === 10403 ){message.error(data.msg)localStorage.removeItem("token")location.href="/login"return}// 其他错误message.error(data.msg)return Promise.reject(data)},// 拦截错误响应error => {return Promise.reject(error);}
)// GET 请求
function get(url: string, params: any) {return req.get(url, {params})
}// POST 请求
function post(url: string, data: any) {return req.post(url, data)
}// 导出
export default {req,get,post,
}
实现加载状态组件
安装 less 依赖
yarn add -D less
src/components/loading/Loading.less
// 请求加载状态
.request-loading {position: fixed;top: 0;left: 0;bottom: 0;right: 0;display: flex;align-items: center;justify-content: center;font-size: 20px;
}
src/components/loading/Loading.tsx
import {Spin} from "antd";
import "./Loading.less"export default function Loading() {return <Spin size="large" className="request-loading"/>
}
src/components/loading/index.tsx
import ReactDOM from "react-dom/client";
import Loading from "@/components/loading/Loading.tsx";// 显示加载状态
const showLoading = () => {const dom = document.getElementById("loading");ReactDOM.createRoot(dom as HTMLElement).render(<Loading/>)
}export {showLoading,
}
src/api/request.ts
修改请求拦截器。
核心代码:
req.interceptors.request.use(// 拦截配置并更新配置config => {// 请求开始之前要展示加载状态showLoading()// 获取登录tokenconst token = localStorage.getItem("token")// 使用 JWT Tokenif (token) {config.headers.Authorization = "Bearer " + token}// 将修改后的配置返回return {...config}},// 拦截错误并注入错误信息error => {return Promise.reject(error);}
)
完整代码:
import axios from "axios";
import {message} from "antd";
import {showLoading} from "@/components/loading/Index.tsx";// 创建实例
const req = axios.create({baseURL: '/api',timeout: 3000,timeoutErrorMessage: "请求超时,请稍后再试",withCredentials: true, // 跨域headers: {'Content-Type': 'application/json',}
})// 请求拦截器
req.interceptors.request.use(// 拦截配置并更新配置config => {// 请求开始之前要展示加载状态showLoading()// 获取登录tokenconst token = localStorage.getItem("token")// 使用 JWT Tokenif (token) {config.headers.Authorization = "Bearer " + token}// 将修改后的配置返回return {...config}},// 拦截错误并注入错误信息error => {return Promise.reject(error);}
)// 响应拦截器
req.interceptors.response.use(// 拦截正常响应response=>{// 获取服务端响应的数据const data = response.data// 响应成功if (data.code===10000 && data.status === true){return data.data}// 响应失败:权限错误if (data.code === 10401 || data.status === 10403 ){message.error(data.msg)localStorage.removeItem("token")location.href="/login"return}// 其他错误message.error(data.msg)return Promise.reject(data)},// 拦截错误响应error => {return Promise.reject(error);}
)// GET 请求
export function get(url: string, params: any) {return req.get(url, {params})
}// POST 请求
function post(url: string, data: any) {return req.post(url, data)
}// 导出
export default {req,get,post,
}
src/page/Login.tsx
在登录页面测试。
import {useEffect} from "react";
import {get} from "@/api/request.ts";export default function Login() {useEffect(() => {get("/test", null).then(data => {console.log(data);}).catch(err => {console.log(err);})}, [])return (<div>Login</div>)
}
隐藏加载状态
修改 src/components/loading/index.tsx
核心代码:
const hideLoading = () => {if (count < 0) returncount--if (count === 0) {const dom = document.getElementById("loading") as HTMLElementlet root = document.getElementById("root") as HTMLElementroot.removeChild(dom)}
}
完整代码:
import ReactDOM from "react-dom/client";
import Loading from "@/components/loading/Loading.tsx";let count = 0; // 请求计数// 显示加载状态
const showLoading = () => {if (count === 0) {let root = document.getElementById("root") as HTMLElementconst dom = document.createElement("div")dom.setAttribute("id", "loading")root.appendChild(dom)ReactDOM.createRoot(dom as HTMLElement).render(<Loading/>)}count++
}// 隐藏加载状态
const hideLoading = () => {if (count < 0) returncount--if (count === 0) {const dom = document.getElementById("loading") as HTMLElementlet root = document.getElementById("root") as HTMLElementroot.removeChild(dom)}
}export {showLoading,hideLoading,
}
在响应拦截器中隐藏加载状态
修改 src/api/request.ts
核心代码:
req.interceptors.response.use(// 拦截正常响应response=>{// 关闭加载状态hideLoading()// 获取服务端响应的数据const data = response.data// 响应成功if (data.code===10000 && data.status === true){return data.data}// 响应失败:权限错误if (data.code === 10401 || data.status === 10403 ){message.error(data.msg)localStorage.removeItem("token")location.href="/login"return}// 其他错误message.error(data.msg)return Promise.reject(data)},// 拦截错误响应error => {// 关闭加载状态hideLoading()// 返回错误信息message.error(error.message)return Promise.reject(error.message);}
)
完整代码:
import axios from "axios";
import {message} from "antd";
import {hideLoading, showLoading} from "@/components/loading/Index.tsx";// 创建实例
const req = axios.create({baseURL: '/api',timeout: 3000,timeoutErrorMessage: "请求超时,请稍后再试",withCredentials: true, // 跨域headers: {'Content-Type': 'application/json',}
})// 请求拦截器
req.interceptors.request.use(// 拦截配置并更新配置config => {// 请求开始之前要展示加载状态showLoading()// 获取登录tokenconst token = localStorage.getItem("token")// 使用 JWT Tokenif (token) {config.headers.Authorization = "Bearer " + token}// 将修改后的配置返回return {...config}},// 拦截错误并注入错误信息error => {// 关闭加载状态hideLoading()// 返回错误信息return Promise.reject(error);}
)// 响应拦截器
req.interceptors.response.use(// 拦截正常响应response=>{// 关闭加载状态hideLoading()// 获取服务端响应的数据const data = response.data// 响应成功if (data.code===10000 && data.status === true){return data.data}// 响应失败:权限错误if (data.code === 10401 || data.status === 10403 ){message.error(data.msg)localStorage.removeItem("token")location.href="/login"return}// 其他错误message.error(data.msg)return Promise.reject(data)},// 拦截错误响应error => {// 关闭加载状态hideLoading()// 返回错误信息message.error(error.message)return Promise.reject(error.message);}
)// GET 请求
export function get(url: string, params: any) {return req.get(url, {params})
}// POST 请求
function post(url: string, data: any) {return req.post(url, data)
}// 导出
export default {req,get,post,
}