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

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("登录失败");
  }
};
相关推荐
用户0934077735142 小时前
HarmonyOS WPS Open SDK 工程实践:把 registerApp 做成就绪门禁
typescript·harmonyos
Hello.Reader3 小时前
tsrs 技术解析用 Rust 移植 TypeScript 7,类型检查还能怎样提速?
开发语言·rust·typescript
汤米粥7 小时前
2026年主流前端技术框架
vue·react·elementplus·tailwind css·angular‌·svelte‌·bootstrap‌
codigger12 小时前
Vue nextTick 到底在等什么?一篇讲透原理与那些年踩过的坑
程序员·vue·编程·异步更新·#人工智能
德尔塔A1 天前
中文全文检索加向量,我用 SQLite 做到零依赖
typescript
wflynn1 天前
GitHub 今日推荐|rea:用 MCP 把反编译器和 AI agent 接到一起的逆向工具
typescript·开源·github·agent·agent-skills·binary-analysis
德尔塔A1 天前
AI 改了 300KB 的文件,我让浏览器一屏都不多拿
typescript
德尔塔A1 天前
给 Agent 写终端界面,我一个 UI 库都没装
typescript
德尔塔A1 天前
同一条命令,在 Windows 上炸了三种方式
typescript
德尔塔A1 天前
同一个会话,终端和浏览器同时开着会发生什么
typescript