1. 配置响应拦截器
TypeScript
import axios from 'axios';
const myAxios = axios.create({
baseURL: 'http://localhost:8080/api/',
});
myAxios.defaults.withCredentials = true;
// 请求拦截器
myAxios.interceptors.request.use(function (config) {
// Do something before request is sent
console.log("发送请求啦...");
return config;
}, function (error) {
// Do something with request error
return Promise.reject(error);
});
// 响应拦截器
myAxios.interceptors.response.use(function (response) {
// Do something with response data
console.log("接收到请求啦...");
return response.data;
}, function (error) {
// Do something with response error
return Promise.reject(error);
});
export default myAxios;
2. 强制跳转到登录页面
- 有些页面只允许用户登录后查看
- 未登录用户没有权限,后端返回 40100
- 前端接收到 40100 则跳转到登录页面,要求用户进行登录
TypeScript
// 响应拦截器
myAxios.interceptors.response.use(function (response) {
// Do something with response data
console.log("接收到请求啦...");
// 未登录,强制跳转到登录页
if (response?.data?.code === 40100) {
const redirectUrl = window.location.href;
window.location.href = `/user/login?redirect${redirectUrl}`;
}
return response.data;
}, function (error) {
// Do something with response error
return Promise.reject(error);
});
export default myAxios;
3. 登录成功跳转到登录之前的页面
- 记录当前页面,拼接到 url 的 redirect 后面
- 登录成功,取出 redirect,重定向到 redirect
TypeScript
// 提交登录表单信息
const onSubmit = async (values) => {
const res = await myAxios.post('/user/login', {
userAccount: userAccount.value,
userPassword: userPassword.value,
})
console.log(res, "用户登录");
if (res.code === 0 && res.data) {
// 返回到之前的页面
const redirectUrl = route.query?.redirect as string ?? '/';
window.location.href=redirectUrl;
} else {
Toast.fail("登录失败");
}
};