이렇게 하면 데이터 가져오기가 간편해집니다. 하지만 모두 인증이 필요한 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에서 데이터를 가져와야 할 때마다 useFetch 대신 useAuthFetch를 사용하면 인증이 원활하게 처리됩니다.
Welcome back {{ user.email }}loading...
네트워크 호출을 검사하면 baseUrl이 정확하고 Authorization 헤더가 존재하는 것을 확인할 수 있습니다.
내 인터셉터에 애플리케이션에 Sentry와 같은 도구가 있는 경우 유용할 수 있는 몇 가지 로그를 추가했습니다.
Nuxt에 Sentry를 추가하는 방법: 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\\',});
백엔드가 tracingId를 반환하는 경우 센트리가 포함된 태그와 컨텍스트를 추가하여 오류를 엔드포인트와 연결할 수도 있습니다.
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를 사용해 본 적이 있다면 Fetch composable을 편리하게 사용하는 방법을 접했을 것입니다.
이렇게 하면 데이터 가져오기가 간편해집니다. 하지만 모두 인증이 필요한 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에서 데이터를 가져와야 할 때마다 useFetch 대신 useAuthFetch를 사용하면 인증이 원활하게 처리됩니다.
Welcome back {{ user.email }}loading...
네트워크 호출을 검사하면 baseUrl이 정확하고 Authorization 헤더가 존재하는 것을 확인할 수 있습니다.
내 인터셉터에 애플리케이션에 Sentry와 같은 도구가 있는 경우 유용할 수 있는 몇 가지 로그를 추가했습니다.
Nuxt에 Sentry를 추가하는 방법: 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', });
백엔드가 tracingId를 반환하는 경우 센트리가 포함된 태그와 컨텍스트를 추가하여 오류를 엔드포인트와 연결할 수도 있습니다.
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