這簡化了資料獲取,但是如果您有大量都需要身份驗證的 API 怎麼辦? 為每個呼叫添加標頭很快就會變得乏味。
輸入攔截器。
為了添加全域攔截器,我們將圍繞 $fetch 建立一個自訂的可組合包裝器。當您的 API 呼叫始終需要授權標頭時,這尤其有價值。
作為基礎,讓我們使用我之前關於 Nuxt 3 中的身份驗證的部落格文章中的相同項目。
讓我們先在可組合資料夾 composables/useAuthFetch.ts 下建立一個新的可組合項目
import type { UseFetchOptions } from \\'nuxt/app\\';const useAuthFetch = (url: string | (() => string), options: UseFetchOptions= {}) => { const customFetch = $fetch.create({ baseURL: \\'https://dummyjson.com\\', onRequest({ options }) { const token = useCookie(\\'token\\'); if (token?.value) { console.log(\\'[fetch request] Authorization header created\\'); options.headers = options.headers || {}; options.headers.Authorization = `Bearer ${token.value}`; } }, onResponse({ response }) { console.info(\\'onResponse \\', { endpoint: response.url, status: response?.status, }); }, onResponseError({ response }) { const statusMessage = response?.status === 401 ? \\'Unauthorized\\' : \\'Response failed\\'; console.error(\\'onResponseError \\', { endpoint: response.url, status: response?.status, statusMessage, }); throw showError({ statusCode: response?.status, statusMessage, fatal: true, }); }, }); return useFetch(url, { ...options, $fetch: customFetch, });};export default useAuthFetch;
解釋:
您可以在此處找到有關攔截器的更多資訊
現在,每當您需要從經過驗證的 API 取得資料時,只需使用 useAuthFetch 而不是 useFetch,授權將無縫處理。
Welcome back {{ user.email }}loading...
當您檢查網路呼叫時,您可以看到 baseUrl 是正確的並且存在 Authorization 標頭
在我的攔截器中,我添加了一些日誌,如果您的應用程式中有像 Sentry 這樣的工具,這些日誌會很有用。
如何將Sentry加入Nuxt:https://www.lichter.io/articles/nuxt3-sentry-recipe/
在 onRequest 攔截器中,您可以為哨兵添加麵包屑
import * as Sentry from \\'@sentry/vue\\';Sentry.addBreadcrumb({ type: \\'http\\', category: \\'xhr\\', message: ``, data: { url: `${options.baseURL}${request}`, }, level: \\'info\\',});
如果您的後端返回追蹤Id,您也可以使用哨兵添加標籤和上下文,以將錯誤與端點連結
onResponseError 您可以新增上下文麵包屑和標籤
import * as Sentry from \\'@sentry/vue\\';Sentry.setContext(\\'http-error\\', { endpoint: response?.url, tracingId: 123, status: response?.status,});Sentry.addBreadcrumb({ type: \\'http\\', category: \\'xhr\\', message: ``, data: { url: response?.url, status_code: response?.status, }, level: \\'error\\',});Sentry.setTag(\\'tracingId\\', \\'123\\');
將tracingId替換為後端傳回的任何自訂追蹤日誌
","image":"http://www.luping.net/uploads/20241003/172795752666fe8a16368ef.png","datePublished":"2024-11-08T14:15:37+08:00","dateModified":"2024-11-08T14:15:37+08:00","author":{"@type":"Person","name":"luping.net","url":"https://www.luping.net/articlelist/0_1.html"}}如果您使用過 Nuxt,您可能遇到過方便的 useFetch 可組合項目:
這簡化了資料獲取,但是如果您有大量都需要身份驗證的 API 怎麼辦? 為每個呼叫添加標頭很快就會變得乏味。
輸入攔截器。
為了添加全域攔截器,我們將圍繞 $fetch 建立一個自訂的可組合包裝器。當您的 API 呼叫始終需要授權標頭時,這尤其有價值。
作為基礎,讓我們使用我之前關於 Nuxt 3 中的身份驗證的部落格文章中的相同項目。
讓我們先在可組合資料夾 composables/useAuthFetch.ts 下建立一個新的可組合項目
import type { UseFetchOptions } from 'nuxt/app'; const useAuthFetch = (url: string | (() => string), options: UseFetchOptions= {}) => { const customFetch = $fetch.create({ baseURL: 'https://dummyjson.com', onRequest({ options }) { const token = useCookie('token'); if (token?.value) { console.log('[fetch request] Authorization header created'); options.headers = options.headers || {}; options.headers.Authorization = `Bearer ${token.value}`; } }, onResponse({ response }) { console.info('onResponse ', { endpoint: response.url, status: response?.status, }); }, onResponseError({ response }) { const statusMessage = response?.status === 401 ? 'Unauthorized' : 'Response failed'; console.error('onResponseError ', { endpoint: response.url, status: response?.status, statusMessage, }); throw showError({ statusCode: response?.status, statusMessage, fatal: true, }); }, }); return useFetch(url, { ...options, $fetch: customFetch, }); }; export default useAuthFetch;
解釋:
您可以在此處找到有關攔截器的更多資訊
現在,每當您需要從經過驗證的 API 取得資料時,只需使用 useAuthFetch 而不是 useFetch,授權將無縫處理。
Welcome back {{ user.email }}loading...
當您檢查網路呼叫時,您可以看到 baseUrl 是正確的並且存在 Authorization 標頭
在我的攔截器中,我添加了一些日誌,如果您的應用程式中有像 Sentry 這樣的工具,這些日誌會很有用。
如何將Sentry加入Nuxt:https://www.lichter.io/articles/nuxt3-sentry-recipe/
在 onRequest 攔截器中,您可以為哨兵添加麵包屑
import * as Sentry from '@sentry/vue'; Sentry.addBreadcrumb({ type: 'http', category: 'xhr', message: ``, data: { url: `${options.baseURL}${request}`, }, level: 'info', });
如果您的後端返回追蹤Id,您也可以使用哨兵添加標籤和上下文,以將錯誤與端點連結
onResponseError 您可以新增上下文麵包屑和標籤
import * as Sentry from '@sentry/vue'; Sentry.setContext('http-error', { endpoint: response?.url, tracingId: 123, status: response?.status, }); Sentry.addBreadcrumb({ type: 'http', category: 'xhr', message: ``, data: { url: response?.url, status_code: response?.status, }, level: 'error', }); Sentry.setTag('tracingId', '123');
將tracingId替換為後端傳回的任何自訂追蹤日誌
免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。
Copyright© 2022 湘ICP备2022001581号-3