跳至主要内容
版本:11.x

自定义标题

使用 httpBatchLinkhttpLink 时,可以在配置中自定义 headers 选项。

headers 可以是对象或函数。如果它是函数,它将在每次 HTTP 请求时动态调用。

utils/trpc.ts
ts
// Import the router type from your server file
import 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.ts
ts
// Import the router type from your server file
import 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.tsx
ts
const loginMut = trpc.auth.login.useMutation({
onSuccess(opts) {
token = opts.accessToken;
},
});
pages/auth.tsx
ts
const loginMut = trpc.auth.login.useMutation({
onSuccess(opts) {
token = opts.accessToken;
},
});

token 可以是任何你想要的东西。完全由你决定它是否只是一个客户端变量,你可以在成功时更新它的值,或者你是否存储令牌并从本地存储中提取它。