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

HTTP 链接

httpLink 是一个 终止链接,它通过 HTTP 将 tRPC 操作发送到 tRPC 过程。

httpLink 支持 POST 和 GET 请求。

使用

您可以导入并将 httpLink 添加到 links 数组,如下所示

client/index.ts
ts
import { createTRPCClient, httpLink } from '@trpc/client';
import type { AppRouter } from '../server';
const client = createTRPCClient<AppRouter>({
links: [
httpLink({
url: 'http://localhost:3000',
// transformer,
}),
],
});
client/index.ts
ts
import { createTRPCClient, httpLink } from '@trpc/client';
import type { AppRouter } from '../server';
const client = createTRPCClient<AppRouter>({
links: [
httpLink({
url: 'http://localhost:3000',
// transformer,
}),
],
});

httpLink 函数接受一个具有 HTTPLinkOptions 形状的选项对象。

ts
export interface HTTPLinkOptions {
url: string;
/**
* Add ponyfill for fetch
*/
fetch?: typeof fetch;
/**
* Add ponyfill for AbortController
*/
AbortController?: typeof AbortController | null;
/**
* Data transformer
* @link https://trpc.node.org.cn/docs/v11/data-transformers
**/
transformer?: DataTransformerOptions;
/**
* Headers to be set on outgoing requests or a callback that of said headers
* @link https://trpc.node.org.cn/docs/v10/header
*/
headers?:
| HTTPHeaders
| ((opts: { op: Operation }) => HTTPHeaders | Promise<HTTPHeaders>);
/**
* Send all requests as POSTS requests regardless of the procedure type
* The server must separately allow overriding the method. See:
* @link https://trpc.node.org.cn/docs/rpc
*/
methodOverride?: 'POST';
}
ts
export interface HTTPLinkOptions {
url: string;
/**
* Add ponyfill for fetch
*/
fetch?: typeof fetch;
/**
* Add ponyfill for AbortController
*/
AbortController?: typeof AbortController | null;
/**
* Data transformer
* @link https://trpc.node.org.cn/docs/v11/data-transformers
**/
transformer?: DataTransformerOptions;
/**
* Headers to be set on outgoing requests or a callback that of said headers
* @link https://trpc.node.org.cn/docs/v10/header
*/
headers?:
| HTTPHeaders
| ((opts: { op: Operation }) => HTTPHeaders | Promise<HTTPHeaders>);
/**
* Send all requests as POSTS requests regardless of the procedure type
* The server must separately allow overriding the method. See:
* @link https://trpc.node.org.cn/docs/rpc
*/
methodOverride?: 'POST';
}

参考

您可以在 GitHub 上查看此链接的源代码。