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

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("登录失败");
  }
};
相关推荐
执剑、天涯23 分钟前
通过一个typescript的小游戏,使用单元测试实战(二)
javascript·typescript·单元测试
chéng ௹3 小时前
Vue3+Ts+Element Plus 权限菜单控制节点
前端·javascript·vue.js·typescript
bdawn10 小时前
Vue3 项目首屏加载性能优化全攻略
性能优化·vue·策略·分包
Orange_sparkle16 小时前
若依使用基本步骤
java·vue
武清伯MVP1 天前
阮一峰《TypeScript 教程》学习笔记——基本用法
笔记·学习·typescript
肖祥1 天前
uni-app x封装request,统一API接口请求
vue
阿喵派我来抓鱼1 天前
深入理解 AI 流式接口:从请求到响应的完整解析
react.js·ai·前端框架·vue
Ciito2 天前
查看Vue项目当前的Vue CLI版本号
vue
肖祥2 天前
uni-app x使用uview-plus
vue
dcloud_jibinbin2 天前
【uniapp】体验优化:开源工具集 uni-toolkit 发布
前端·webpack·性能优化·小程序·uni-app·vue