浪花 - 响应拦截器(强制登录)

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("登录失败");
  }
};
相关推荐
shawxlee9 小时前
vue3+elementplus+sass/scss安装配置教程:使用svg图标、引入外部字体、定义变量模块、修改组件样式、一键切换主题等
vue·sass·svg·字体·element·scss·主题样式
凌云拓界10 小时前
NodeVerdict:Node.js 原生诊断数据可视化工具
信息可视化·架构·typescript·开源·node.js·github·bug
苏灿烤鱼12 小时前
GitHub Trending 榜首|GitHub #1 拆解|为什么「持久工作台」比临时沙箱更值得关注?(08.06)技术拆解
人工智能·typescript·agent
弹简特12 小时前
【Vue3速成】07-vue3异步请求之Axios-01
vue·axios
用户938515635071 天前
从"坐电梯"到"前端路由"——深入理解 Hash 路由原理
前端·typescript·全栈
苏灿烤鱼1 天前
GitHub Trending 榜首|腾讯 Agent 记忆库技术拆解:分层记忆 vs 向量堆,让 AI 不再反复问
typescript·开源·agent
用户938515635071 天前
React 组件设计的三个层次:从类型约束到状态归属,再到纯展示
typescript·全栈
A24207349301 天前
Vue3 + TypeScript:后端数据在表格内渲染后进行增删改的完整实现步骤
前端·javascript·typescript
水獭比特1 天前
AI 视频生成不是一次 HTTP 请求:先把长任务状态机补齐
人工智能·typescript
弹简特2 天前
【Vue3速成】06-vue3官方库路由机制之Pinia状态管理
vue·pinia