指尖上的记忆指尖上的记忆
首页
  • 基础
  • Laravel框架
  • Symfony框架
  • 基础
  • Gin框架
  • 基础
  • Spring框架
  • 命令
  • Nginx
  • Ai
  • Deploy
  • Docker
  • K8s
  • Micro
  • RabbitMQ
  • Mysql
  • PostgreSsql
  • Redis
  • MongoDb
  • Html
  • Js
  • 前端
  • 后端
  • Git
  • 知识扫盲
  • Golang
🌟 gitHub
首页
  • 基础
  • Laravel框架
  • Symfony框架
  • 基础
  • Gin框架
  • 基础
  • Spring框架
  • 命令
  • Nginx
  • Ai
  • Deploy
  • Docker
  • K8s
  • Micro
  • RabbitMQ
  • Mysql
  • PostgreSsql
  • Redis
  • MongoDb
  • Html
  • Js
  • 前端
  • 后端
  • Git
  • 知识扫盲
  • Golang
🌟 gitHub

nuxt3在middleware中请求api,获取数据,判断用户登录状态,这个功能主要是,有些页面是需要用户登录以后才能访问的,避免用户直接访问到 需要登陆的页面,所以就在需要登的页面设置middleware,进行控制,具体代码如下,我自定义的
middleware/learnAuth.ts:

// @ts-ignore
import {defineNuxtRouteMiddleware, navigateTo, useRuntimeConfig} from "#app"
import utils from '../utils/utils'

import {} from "nuxt/app";// 开始将 navigateTo, useRuntimeConfig 全部都放在这个里面,但是一运行就报:Failed to import dynamic modules,后来在官方的issue 有人直接放到了 #app, 我也这样改了,再运行就不会报错了,这里 import {} 是为了的代码不报红,去掉import {} from "nuxt/app" 也是可以的,只是下面的代码会报红,很不舒服,所以就加上了; 或者在报红的代码那里加上:// @ts-ignore 也是可以的

import {createError} from "h3";

// async function isJoinTheCourse(id){
//     let userInfo = utils.getUserInfo()
//     await $fetch('/api/user/course', {
//         method: 'post',
//         body: {userId: userInfo.id, courseId: id},
//         headers: {'X-Requested-With': 'XMLHttpRequest'},
//     })
// }
export default defineNuxtRouteMiddleware(async (to, from) => {
    if (process.server) return // 跳过server端验证 直接验证client 端

    let isLogin = utils.isLogin()
    const config = useRuntimeConfig()
    let loginUrl = config.public.envData.VITE_LOGIN_URL

    if (isLogin){
        console.log(loginUrl)
      // window.location.href = loginUrl;
    }

    // isJoinTheCourse(to.query.id).then(r => {
    //     console.log(r)
    // })


    const result = await $fetch('/api/user/test') // 调用api 只能通过$fetch 这个全局方法实现
    console.log(result)
    if (result.code != 0){
        if (result.code == 1){
            return navigateTo('/', { redirectCode: 403 })
        }else {
            throw createError({ statusCode: 404, statusMessage: 'Page Not Found' })
        }
    }else {
        return
    }
})


//精简以后的版本,只做是否登录验证,接口调用去掉了
// @ts-ignore
import {defineNuxtRouteMiddleware, navigateTo, useRuntimeConfig} from "#app"
import utils from '../utils/utils'
export default defineNuxtRouteMiddleware(async (to, from) => {
    // @ts-ignore
    if (process.client) return
    let isLogin = utils.isLogin()
    const config = useRuntimeConfig()
    let loginUrl = config.public.envData.VITE_LOGIN_URL

    if (!isLogin){
        return navigateTo(loginUrl, { redirectCode: 403 , external: true})
    }
})

当初按之前的写法一直报:Failed to import dynamic modules,后来查看issue 发现另外一种写法,就如上所示