自定义标头
非官方测试版翻译
本页面由 PageTurner AI 翻译(测试版)。未经项目官方认可。 发现错误? 报告问题 →
使用 httpBatchLink 或 httpLink 时,可以在配置中自定义标头选项。
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(config) {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(config) {return {links: [httpBatchLink({url: 'http://localhost:3000/api/trpc',/*** Headers will be called on each request.*/headers() {return {Authorization: token,};},}),],};},});
认证登录示例
pages/auth.tsxtsconst loginMut = trpc.auth.login.useMutation({onSuccess(opts) {token = opts.accessToken;},});
pages/auth.tsxtsconst loginMut = trpc.auth.login.useMutation({onSuccess(opts) {token = opts.accessToken;},});
token 的具体形式完全由开发者决定:既可以是客户端变量(在成功时更新其值),也可以存储在本地存储中(使用时从中获取)。