mirror of
https://github.com/rustfs/console.git
synced 2026-09-19 09:52:25 +08:00
32 lines
784 B
TypeScript
32 lines
784 B
TypeScript
import ApiClient from "~/lib/api-client"
|
|
|
|
export default defineNuxtPlugin((nuxtApp) => {
|
|
const token = useCookie('token')
|
|
|
|
const fetch = $fetch.create({
|
|
baseURL: '/api',
|
|
onRequest({ request, options }) {
|
|
if (token) {
|
|
options.headers.set('Authorization', `Bearer ${token}`)
|
|
}
|
|
},
|
|
onResponse({ response }) {
|
|
console.log('[API] response', response)
|
|
},
|
|
async onResponseError({ response }: { response: { status: number } }) {
|
|
if (response.status === 401) {
|
|
token.value = undefined
|
|
await nuxtApp.runWithContext(() => navigateTo('/auth/login'))
|
|
}
|
|
}
|
|
})
|
|
|
|
// Expose to useNuxtApp().$api, useNuxtApp().$apiFetch
|
|
return {
|
|
provide: {
|
|
api: new ApiClient(fetch),
|
|
apiFetch: fetch
|
|
}
|
|
}
|
|
})
|