跳至主内容
版本:10.x

跨域发送 Cookies

非官方测试版翻译

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

如果您的 API 与前端处于不同的源(origin),且需要向其发送 Cookies,则需在服务器端启用 CORS,并通过在 fetch 请求中添加 {credentials: "include"} 选项来发送 Cookies。

可以按照以下方式修改 tRPC 所使用的 fetch 函数的参数。

app.ts
ts
import { createTRPCProxyClient, httpBatchLink } from '@trpc/client';
const client = createTRPCProxyClient<AppRouter>({
links: [
httpBatchLink({
url: 'YOUR_SERVER_URL',
fetch(url, options) {
return fetch(url, {
...options,
credentials: 'include',
});
},
}),
],
});
app.ts
ts
import { createTRPCProxyClient, httpBatchLink } from '@trpc/client';
const client = createTRPCProxyClient<AppRouter>({
links: [
httpBatchLink({
url: 'YOUR_SERVER_URL',
fetch(url, options) {
return fetch(url, {
...options,
credentials: 'include',
});
},
}),
],
});
信息

您还需要通过修改适配器(adapter)或位于 API 前端的 HTTP 服务器来启用 CORS。具体实现方式因适配器类型和基础设施而异,各适配器通常会在适用场景下提供相关文档说明。