自定义请求头
非官方测试版翻译
本页面由 PageTurner AI 翻译(测试版)。未经项目官方认可。 发现错误? 报告问题 →
在使用 Next.js 的 withTRPC 或 React.js 的 createClient 时,可以在配置中自定义 headers 选项。
headers 可以是静态对象,也可以是动态函数。当采用函数形式时,它会在每次 HTTP 请求时被动态调用。
_app.tsxtsimport type { AppRouter } from '@/server/routers/app';import { withTRPC } from '@trpc/next';import { AppType } from 'next/dist/shared/lib/utils';export let token: string;const MyApp: AppType = ({ Component, pageProps }) => {return <Component {...pageProps} />;};export default withTRPC<AppRouter>({config(config) {return {links: [httpBatchLink({/** headers are called on every request */headers: () => {return {Authorization: token,};},}),],};},})(MyApp);
_app.tsxtsimport type { AppRouter } from '@/server/routers/app';import { withTRPC } from '@trpc/next';import { AppType } from 'next/dist/shared/lib/utils';export let token: string;const MyApp: AppType = ({ Component, pageProps }) => {return <Component {...pageProps} />;};export default withTRPC<AppRouter>({config(config) {return {links: [httpBatchLink({/** headers are called on every request */headers: () => {return {Authorization: token,};},}),],};},})(MyApp);
认证登录示例
pages/auth.tsxtsconst loginMut = trpc.useMutation(['auth.login'], {onSuccess({ accessToken }) {token = accessToken;},});
pages/auth.tsxtsconst loginMut = trpc.useMutation(['auth.login'], {onSuccess({ accessToken }) {token = accessToken;},});
token 的具体形式完全由开发者决定:既可以是客户端变量(在成功时更新其值),也可以存储在本地存储中(使用时从中获取)。