Skip to main content
Version: 10.x

跨域发送 cookie

如果你的 API 驻留在与前端不同的源上,并且你希望向其发送 cookie,则你需要在服务器上启用 CORS,并通过提供要获取的选项 {credentials: "include"} 来随你的请求发送 cookie。

¥If your API resides on a different origin than your front-end and you wish to send cookies to it, you will need to enable CORS on your server and send cookies with your requests by providing the option {credentials: "include"} to fetch.

提供给 tRPC 使用的 fetch 函数的参数可以修改如下。

¥The arguments provided to the fetch function used by tRPC can be modified as follow.

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。执行此操作的最佳方法因适配器和托管基础架构而异,并且各个适配器通常会在适用的情况下记录此过程。

¥You also need to enable CORS on your server by modifying your adapter, or the HTTP server which fronts your API. The best way to do this varies adapter-by-adapter and based on your hosting infrastructure, and individual adapters generally document this process where applicable.