请求头
非官方测试版翻译
本页面由 PageTurner AI 翻译(测试版)。未经项目官方认可。 发现错误? 报告问题 →
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 的具体形式完全由开发者决定:既可以是客户端变量(在成功时更新其值),也可以存储在本地存储中(使用时从中获取)。