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

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("登录失败");
  }
};
相关推荐
钛态18 小时前
前端安全防线:CSRF 攻击链路与双重 Token 校验的工程实现
前端·vue·react·web
zhz52141 天前
GIS项目中空间参考转换与MBTiles偏移:问题成因、解法与避坑
python·vue·gis
钛态1 天前
AI 组件生成评测:别只看页面能不能渲染
前端·vue·react·web
濮水大叔1 天前
在 DTO 中使用 Form Layout 配置复杂表单,支持 Tabs/Groups/Sections
vue.js·typescript·node.js
万亿少女的梦1682 天前
基于Spring Boot、Vue与MySQL的高校实习信息管理系统设计与实现
spring boot·mysql·vue·权限管理·restful api
用户0934077735142 天前
HarmonyOS WPS Open SDK 实践:用能力分层重构 OpenFileRequest
typescript·harmonyos
gis开发之家3 天前
vue3直击架构痛点 依赖倒置与接口隔离——打造坚如磐石的插件与高阶组件(HOC)模式
javascript·架构·typescript·前端框架·vue3
冬枳3 天前
基于OpenSeagragon封装的前端病理切片展示组件
前端·typescript
退休倒计时3 天前
【每日一题】LeetCode 287. 寻找重复数 TypeScript
算法·leetcode·typescript
小堂子这厢有礼了3 天前
Chet.QuartzNet.UI v2.3.0 大更新!表格重构 + 系统配置 + 分析页全面升级!
前端·后端·ui·重构·c#·vue