// plugins/api.ts
export default defineNuxtPlugin((nuxtApp) => {
const { token } = useAuth()
const runtimeConfig = useRuntimeConfig()
const api = $fetch.create({
baseURL: runtimeConfig.public.apiBaseUrl,
onRequest({ request, options, error }) {
if (token.value) {
const headers = options.headers ||= {}
if (Array.isArray(headers)) {
headers.push(['Authorization', `${token.value}`])
} else if (headers instanceof Headers) {
headers.set('Authorization', `${token.value}`)
} else {
headers.Authorization = `${token.value}`
}
}
},
async onResponseError({ response }) {
if (response.status === 401) {
await nuxtApp.runWithContext(() => navigateTo('/login'))
}
}
})
// Expose to useNuxtApp().$api
return {
provide: {
api
}
}
})
// plugins/api.ts
export default defineNuxtPlugin((nuxtApp) => {
const { token } = useAuth()
const runtimeConfig = useRuntimeConfig()
const api = $fetch.create({
baseURL: runtimeConfig.public.apiBaseUrl,
onRequest({ request, options, error }) {
if (token.value) {
const headers = options.headers ||= {}
if (Array.isArray(headers)) {
headers.push(['Authorization', `${token.value}`])
} else if (headers instanceof Headers) {
headers.set('Authorization', `${token.value}`)
} else {
headers.Authorization = `${token.value}`
}
}
},
async onResponseError({ response }) {
if (response.status === 401) {
await nuxtApp.runWithContext(() => navigateTo('/login'))
}
}
})
// Expose to useNuxtApp().$api
return {
provide: {
api
}
}
})