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

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("登录失败");
  }
};
相关推荐
文阿花12 小时前
大屏实现方案之-高德
vue·地图·高德
艾利克斯冰14 小时前
TypeScript 静态类型入门教程:可选静态类型与类型推导详
前端·javascript·typescript
Anesthesia丶2 天前
Vite + Svelte + shadcn-svelte 最小化 Demo+Vue3语法对比总结
vue·vite·svelte·shadcn-svelte
孟郎郎2 天前
TimeoutError: The operation was aborted due to timeout at new DOMException
ai·前端框架·npm·vue·pnpm·deepseek
lpd_lt2 天前
AI生成Spring Boot + Vue 3 + MySQL + MyBatis-Plus的项目实战
java·spring boot·vue·ai编程
cup112 天前
[Full Clock 技术复盘] 一、浏览器前端如何实现百毫秒级时间校准?时间 API 推荐、模拟 NTP 算法原理及局限
typescript·开源·api·时钟·时间同步
来杯@Java2 天前
图书管理系统(基于springboot+vue前后端分离的项目)计算机毕业设计java
java·spring boot·spring·vue·毕业设计·mybatis·课程设计
梦想的颜色2 天前
TypeScript 完全指南(上):从零开始掌握类型系统
前端·typescript
烛衔溟2 天前
TypeScript 类的静态成员与静态方法
开发语言·javascript·typescript