헤더
headers 옵션은 다음 HTTP 링크 중 어느 것과도 함께 사용할 수 있습니다: httpBatchLink, httpBatchStreamLink, httpLink 또는 httpSubscriptionLink.
headers는 객체나 함수 모두 가능합니다. 함수인 경우 모든 HTTP 요청마다 동적으로 호출됩니다.
utils/trpc.tstsimport {createTRPCClient ,httpBatchLink } from '@trpc/client';import type {AppRouter } from './server';lettoken : string;export functionsetToken (newToken : string) {/*** You can also save the token to cookies, and initialize from* cookies above.*/token =newToken ;}export consttrpc =createTRPCClient <AppRouter >({links : [httpBatchLink ({url : 'http://localhost:3000',/*** Headers will be called on each request.*/headers () {return {Authorization :token ,};},}),],});
utils/trpc.tstsimport {createTRPCClient ,httpBatchLink } from '@trpc/client';import type {AppRouter } from './server';lettoken : string;export functionsetToken (newToken : string) {/*** You can also save the token to cookies, and initialize from* cookies above.*/token =newToken ;}export consttrpc =createTRPCClient <AppRouter >({links : [httpBatchLink ({url : 'http://localhost:3000',/*** Headers will be called on each request.*/headers () {return {Authorization :token ,};},}),],});
인증 로그인 예시
auth.tstsconstresult = awaittrpc .auth .login .mutate ({username : 'user',password : 'pass' });setToken (result .accessToken );
auth.tstsconstresult = awaittrpc .auth .login .mutate ({username : 'user',password : 'pass' });setToken (result .accessToken );
token는 원하는 값으로 설정할 수 있습니다. 성공 시 값을 업데이트하는 클라이언트 측 변수인지, 아니면 토큰을 저장하고 로컬 스토리지에서 가져오는지는 전적으로 개발자의 선택에 달려 있습니다.