跳至主内容
版本:11.x

请求头

非官方测试版翻译

本页面由 PageTurner AI 翻译(测试版)。未经项目官方认可。 发现错误? 报告问题 →

headers 选项可用于我们所有的 HTTP 链接:httpBatchLinkhttpBatchStreamLinkhttpLinkhttpSubscriptionLink

headers 既可以是对象也可以是函数。如果是函数,则会在每次 HTTP 请求时动态调用。

utils/trpc.ts
ts
import { createTRPCClient, httpBatchLink } from '@trpc/client';
import type { AppRouter } from './server';
 
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 = createTRPCClient<AppRouter>({
links: [
httpBatchLink({
url: 'http://localhost:3000',
/**
* Headers will be called on each request.
*/
headers() {
return {
Authorization: token,
};
},
}),
],
});
utils/trpc.ts
ts
import { createTRPCClient, httpBatchLink } from '@trpc/client';
import type { AppRouter } from './server';
 
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 = createTRPCClient<AppRouter>({
links: [
httpBatchLink({
url: 'http://localhost:3000',
/**
* Headers will be called on each request.
*/
headers() {
return {
Authorization: token,
};
},
}),
],
});

认证登录示例

auth.ts
ts
const result = await trpc.auth.login.mutate({ username: 'user', password: 'pass' });
setToken(result.accessToken);
auth.ts
ts
const result = await trpc.auth.login.mutate({ username: 'user', password: 'pass' });
setToken(result.accessToken);

token 的具体形式完全由开发者决定:既可以是客户端变量(在成功时更新其值),也可以存储在本地存储中(使用时从中获取)。