使用自定义 Fetch 可组合函数
此示例展示了来自 nuxt 的 useFetch 可组合函数的一个便捷封装。它允许你使用默认值和用户认证令牌来自定义 fetch 请求。
customFetch.ts
Open docsexport default defineNuxtPlugin((nuxtApp) => {
const userAuth = useCookie('token')
const config = useRuntimeConfig()
const $customFetch = $fetch.create({
baseURL: config.baseUrl as string ?? 'https://api.nuxt.com',
onRequest({ request, options, error }) {
if (userAuth.value) {
// Add Authorization header
options.headers.set('Authorization', `Bearer ${userAuth.value}`)
}
},
onResponse({ response }) {
// response._data = new myBusinessResponse(response._data)
},
async onResponseError({ response }) {
if (response.status === 401) {
await nuxtApp.runWithContext(() => navigateTo('/login'))
}
},
})
// Expose to useNuxtApp().$customFetch
return {
provide: {
customFetch: $customFetch,
},
}
})