全局路由守卫-登录鉴权

程序员 2024-9-28 21:45:41 76 0 来自 中国
const router = createRouter({  history,  routes,})router.beforeEach(async (to, from) => {  if (to.path === '/' || to.path.startsWith('/welcome') || to.path.startsWith('/sign_in')) {    return true  } else {   const path =  await http.get('/me').then(() => true, () => '/sign_in?return_to=' + to.path)    return true  }})题目1: 上面的代码每次路由跳转的时间都会调用 me 接口
办理方法:假如我们不想每次路由跳转都调用接口我们可以把接口调用写在表面
const promise = http.get('/me')router.beforeEach(async (to, from) => {  if (to.path === '/' || to.path.startsWith('/welcome') || to.path.startsWith('/sign_in') || to.path.startsWith('/start')) {    return true  } else {    const path = await promise.then(() => true, () => '/sign_in?return_to=' + to.path)    return path  }})题目2:上面接口是只调一次了,但是我们登录乐成后页面不会跳转
缘故起因:以登录乐成后跳转 http://localhost:8082/#/sign_in?return_to=/items/create 为例,我们的 /me 接口依赖 jwt,没登录就没有 jwt,以是一开始我们未登录从 items/create 跳到 sign_in 没题目,但是登录乐成后由于我们的 /me 接口只在初始化的时间调用,以是纵然我们登录乐成这个接口还是走的一开始的 catch 以是还是跳到了登录页
办理方法:在用户登录乐成乐成后主动去更新

  • me.tsx
import { AxiosResponse } from "axios";import { http } from "./Http";export let mePromise: Promise<AxiosResponse<{  resource: {    id: number  }}>> | undefinedexport const refreshMe = () => {  mePromise = http.get<{ resource: { id: number }}>('/me')   return mePromise}export const fetchMe = refreshMe

  • signInPage
// 点击登录按钮后refreshMe()router.push(returnTo || '/')

  • main.ts
import { mePromise, fetchMe } from './shared/me';fetchMe()router.beforeEach(async (to, from) => {  if (to.path === '/' || to.path.startsWith('/welcome') || to.path.startsWith('/sign_in') || to.path.startsWith('/start')) {    return true  } else {    const path = await mePromise!.then(() => true, () => '/sign_in?return_to=' + to.path)    return path  }})
您需要登录后才可以回帖 登录 | 立即注册

Powered by CangBaoKu v1.0 小黑屋藏宝库It社区( 冀ICP备14008649号 )

GMT+8, 2024-10-18 16:44, Processed in 0.164459 second(s), 32 queries.© 2003-2025 cbk Team.

快速回复 返回顶部 返回列表