自訂標頭
使用 httpBatchLink
或 httpLink
時,可以在設定中自訂 headers
選項。
headers
可以是物件或函式。如果是函式,則會針對每個 HTTP 要求動態呼叫它。
utils/trpc.tsts
// Import the router type from your server fileimport type { AppRouter } from '@/server/routers/app';import { httpBatchLink } from '@trpc/client';import { createTRPCNext } from '@trpc/next';let token: string;export function setToken(newToken: string) {/*** You can also save the token to cookies, and initialize from* cookies above.*/token = newToken;}export const trpc = createTRPCNext<AppRouter>({config(opts) {return {links: [httpBatchLink({url: 'http://localhost:3000/api/trpc',/*** Headers will be called on each request.*/headers() {return {Authorization: token,};},}),],};},});
utils/trpc.tsts
// Import the router type from your server fileimport type { AppRouter } from '@/server/routers/app';import { httpBatchLink } from '@trpc/client';import { createTRPCNext } from '@trpc/next';let token: string;export function setToken(newToken: string) {/*** You can also save the token to cookies, and initialize from* cookies above.*/token = newToken;}export const trpc = createTRPCNext<AppRouter>({config(opts) {return {links: [httpBatchLink({url: 'http://localhost:3000/api/trpc',/*** Headers will be called on each request.*/headers() {return {Authorization: token,};},}),],};},});
使用驗證登入的範例
pages/auth.tsxts
const loginMut = trpc.auth.login.useMutation({onSuccess(opts) {token = opts.accessToken;},});
pages/auth.tsxts
const loginMut = trpc.auth.login.useMutation({onSuccess(opts) {token = opts.accessToken;},});
token
可以是您想要的任何內容。您是否只將其設為在成功時更新其值的用戶端變數,或者儲存 token 並從本機儲存中提取它,完全由您決定。