初次提交
This commit is contained in:
@@ -0,0 +1,107 @@
|
||||
export default defineNuxtPlugin((nuxtApp) => {
|
||||
if (!import.meta.client) {
|
||||
return
|
||||
}
|
||||
|
||||
// 立即设置请求拦截器,确保在任何API调用之前生效
|
||||
const originalFetch = window.fetch
|
||||
const errorHandler = useErrorHandler()
|
||||
|
||||
// 拦截window.fetch
|
||||
window.fetch = async function (input: RequestInfo | URL, init?: RequestInit): Promise<Response> {
|
||||
// 处理所有API请求 - cookie会自动发送,无需手动添加Authorization头
|
||||
if (typeof input === 'string' && input.startsWith('/api')) {
|
||||
init = init || {}
|
||||
init.headers = init.headers || {}
|
||||
|
||||
// 确保cookie会被发送
|
||||
init.credentials = 'include'
|
||||
}
|
||||
|
||||
const response = await originalFetch(input, init)
|
||||
|
||||
// 检查是否为401错误
|
||||
if (response.status === 401) {
|
||||
const currentPath = window.location.pathname
|
||||
|
||||
// 如果在登录页面,解析错误响应体并抛出具体错误信息
|
||||
if (currentPath === '/login') {
|
||||
try {
|
||||
const errorData = await response.clone().json()
|
||||
const errorMessage = errorData.message || '登录失败,请检查账号密码'
|
||||
return Promise.reject(new Error(errorMessage))
|
||||
} catch (parseError) {
|
||||
return Promise.reject(new Error('登录失败,请检查账号密码'))
|
||||
}
|
||||
}
|
||||
|
||||
// 只有在非登录页面才触发认证失效处理
|
||||
await errorHandler.handle401Error('您的登录信息已失效,请重新登录')
|
||||
return Promise.reject(new Error('Authentication expired'))
|
||||
}
|
||||
|
||||
return response
|
||||
}
|
||||
|
||||
// 初始化认证状态
|
||||
nuxtApp.hook('app:created', async () => {
|
||||
const auth = useAuth()
|
||||
await auth.initAuth()
|
||||
|
||||
// 拦截$fetch请求,确保cookie会被发送
|
||||
const originalUseFetch = nuxtApp.$fetch
|
||||
if (originalUseFetch) {
|
||||
nuxtApp.$fetch = async function (request: any, options: any = {}) {
|
||||
// 为所有API请求确保cookie会被发送
|
||||
if (typeof request === 'string' && request.startsWith('/api')) {
|
||||
options.headers = options.headers || {}
|
||||
// 确保cookie会被发送
|
||||
options.credentials = 'include'
|
||||
}
|
||||
|
||||
try {
|
||||
return await originalUseFetch(request, options)
|
||||
} catch (error: any) {
|
||||
// 检查是否为401错误
|
||||
if (error?.status === 401 || error?.statusCode === 401) {
|
||||
const currentPath = window.location.pathname
|
||||
|
||||
// 如果在登录页面,解析错误信息并抛出具体错误
|
||||
if (currentPath === '/login') {
|
||||
// 从error对象中提取具体错误信息,过滤掉网络请求信息
|
||||
let errorMessage =
|
||||
error?.data?.message || error?.message || '登录失败,请检查账号密码'
|
||||
|
||||
// 如果错误信息包含网络请求格式(如 [POST] "/api/auth/login": <no response>),则提取纯净的错误信息
|
||||
if (typeof errorMessage === 'string') {
|
||||
// 匹配并移除网络请求前缀格式
|
||||
const cleanMessage = errorMessage
|
||||
.replace(/^\[\w+\]\s+"[^"]+":\s+(<no response>\s+)?/, '')
|
||||
.trim()
|
||||
errorMessage = cleanMessage || '登录失败,请检查账号密码'
|
||||
}
|
||||
|
||||
const newError = new Error(errorMessage)
|
||||
throw newError
|
||||
}
|
||||
|
||||
// 只有在非登录页面才触发认证失效处理
|
||||
await errorHandler.handle401Error('您的登录信息已失效,请重新登录')
|
||||
throw error
|
||||
}
|
||||
throw error
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
// 全局错误处理
|
||||
nuxtApp.hook('vue:error', async (error: any) => {
|
||||
if (error?.status === 401 || error?.statusCode === 401) {
|
||||
const currentPath = window.location.pathname
|
||||
if (currentPath !== '/login') {
|
||||
await errorHandler.handle401Error('您的登录信息已失效,请重新登录')
|
||||
}
|
||||
}
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,9 @@
|
||||
// 服务端认证插件已禁用
|
||||
// 在serverless环境中,使用useState会导致状态在不同用户之间共享
|
||||
// 认证状态应该完全由客户端管理,通过API调用获取
|
||||
|
||||
export default defineNuxtPlugin(async (nuxtApp) => {
|
||||
// 服务端插件已禁用,避免状态共享问题
|
||||
// 认证状态将完全由客户端通过API调用管理
|
||||
return
|
||||
})
|
||||
@@ -0,0 +1,51 @@
|
||||
export default defineNuxtPlugin((nuxtApp) => {
|
||||
// 监听并拦截异步 Chunk / 静态资源加载失败的问题(通常是因为服务端重新部署后,旧缓存还在尝试请求被删除的 hash 文件)
|
||||
nuxtApp.hook('app:chunkError', ({ error }) => {
|
||||
console.error('Nuxt Chunk/Asset Loading Failed. Triggering hard reload...', error)
|
||||
|
||||
// 防止无限刷新,使用 sessionStorage 记录
|
||||
const reloadCount = parseInt(sessionStorage.getItem('chunk_reload_count') || '0')
|
||||
if (reloadCount < 3) {
|
||||
sessionStorage.setItem('chunk_reload_count', String(reloadCount + 1))
|
||||
window.location.reload()
|
||||
} else {
|
||||
console.warn('Too many reload attempts for chunk error. Giving up.')
|
||||
}
|
||||
})
|
||||
|
||||
// 页面成功加载后清除刷新计数器
|
||||
nuxtApp.hook('page:finish', () => {
|
||||
sessionStorage.removeItem('chunk_reload_count')
|
||||
})
|
||||
|
||||
// 拦截全局未捕获的 Promise 错误,防止它阻塞后续操作(例如因为插件拦截导致的 'A listener indicated an asynchronous response...' 错误)
|
||||
if (import.meta.client) {
|
||||
window.addEventListener('unhandledrejection', (event) => {
|
||||
const err = event.reason?.message || event.reason?.toString() || ''
|
||||
if (err.includes('message channel closed') || err.includes('A listener indicated')) {
|
||||
// 这是常见的浏览器插件注入引起的无害错误,直接忽略
|
||||
event.preventDefault()
|
||||
}
|
||||
})
|
||||
|
||||
// 监听全局 Error 事件,捕获 CSS 等资源的加载失败
|
||||
window.addEventListener('error', (event) => {
|
||||
const target = event.target as HTMLElement
|
||||
// 检查是否是 link(css) 或 script 的加载错误
|
||||
if (target && (target.tagName === 'LINK' || target.tagName === 'SCRIPT')) {
|
||||
const href = (target as HTMLLinkElement).href || (target as HTMLScriptElement).src
|
||||
if (href && href.includes('/_nuxt/')) {
|
||||
console.warn('Nuxt static asset failed to load:', href)
|
||||
const reloadCount = parseInt(sessionStorage.getItem('asset_reload_count') || '0')
|
||||
if (reloadCount < 2) {
|
||||
sessionStorage.setItem('asset_reload_count', String(reloadCount + 1))
|
||||
// 延迟一点刷新以防频繁请求
|
||||
setTimeout(() => {
|
||||
window.location.reload()
|
||||
}, 1000)
|
||||
}
|
||||
}
|
||||
}
|
||||
}, true) // true = 捕获阶段,以便拦截资源加载错误
|
||||
}
|
||||
})
|
||||
Reference in New Issue
Block a user