Skip to content

节点构建者的 HTTP 请求助手#

n8n 提供了一个灵活的 HTTP 请求助手,它抽象了大部分复杂性。

仅限编程式样式

本文档中的信息适用于使用编程式样式的节点构建。它不适用于声明式样式节点。

用法#

execute 函数内调用助手。

1
2
3
4
5
6
7
8
9
// 如果不需要身份验证
const response = await this.helpers.httpRequest(options);

// 如果需要身份验证
const response = await this.helpers.httpRequestWithAuthentication.call(
	this, 
	'credentialTypeName', // 例如:pipedriveApi
	options,
);

options 是一个对象:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
{
	url: string;
	headers?: object;
	method?: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'HEAD';
	body?: FormData | Array | string | number | object | Buffer | URLSearchParams;
	qs?: object;
	arrayFormat?: 'indices' | 'brackets' | 'repeat' | 'comma';
	auth?: {
		username: string,
		password: string,
	};
	disableFollowRedirect?: boolean;
	encoding?: 'arraybuffer' | 'blob' | 'document' | 'json' | 'text' | 'stream';
	skipSslCertificateValidation?: boolean;
	returnFullResponse?: boolean;
	proxy?: {
		host: string;
		port: string | number;
		auth?: {
			username: string;
			password: string;
		},
		protocol?: string;
	};
	timeout?: number;
	json?: boolean;
}	

url 是必需的。其他字段是可选的。默认方法是 GET

关于可能字段的一些注意事项:

  • body:您可以使用常规 JavaScript 对象作为 JSON 负载,使用缓冲区进行文件上传,使用 FormData 实例进行 multipart/form-data,使用 URLSearchParams 进行 application/x-www-form-urlencoded
  • headers:键值对。
    • 如果 body 是 FormData 实例,则 n8n 自动添加 content-type: multipart/form-data
    • 如果 bodyURLSearchParams 实例,则 n8n 添加 content-type: application/x-www-form-urlencoded
    • 要覆盖此行为,请设置 content-type 标头。
  • arrayFormat:如果您的查询字符串包含数据数组,如 const qs = {IDs: [15,17]}arrayFormat 的值定义 n8n 如何格式化它。
    • indices(默认):{ a: ['b', 'c'] } 作为 a[0]=b&a[1]=c
    • brackets{ a: ['b', 'c'] } 作为 a[]=b&a[]=c
    • repeat{ a: ['b', 'c'] } 作为 a=b&a=c
    • comma{ a: ['b', 'c'] } 作为 a=b,c
  • auth:用于基本身份验证。提供 usernamepassword。n8n 建议省略此项,而使用 helpers.httpRequestWithAuthentication(...) 代替。
  • disableFollowRedirect:默认情况下,n8n 遵循重定向。您可以将此设置为 true 以防止这种情况发生。
  • skipSslCertificateValidation:用于调用没有适当证书的 HTTPS 服务
  • returnFullResponse:不仅返回正文,而是返回包含更多数据的对象,格式如下:{body: body, headers: object, statusCode: 200, statusMessage: 'OK'}
  • encoding:n8n 可以检测内容类型,但您可以指定 arrayBuffer 以接收您可以读取和交互的缓冲区。

示例#

有关示例,请参考 Mattermost 节点

弃用之前的助手#

使用 this.helpers.request(options) 的之前助手实现使用并暴露了 request-promise 库。这在版本 1 中被移除。

为了最小化不兼容性,n8n 对另一个名为 Axios 的库进行了透明转换。

如果您遇到问题,请在社区论坛GitHub 上报告。

迁移到新助手的指南#

新助手更加健壮、库无关且更易于使用。

新节点都应该使用新助手。您应该强烈考虑将现有的自定义节点迁移到新助手。迁移时的主要考虑事项:

  • 接受 url。不接受 uri
  • encoding: null 现在必须是 encoding: arrayBuffer
  • rejectUnauthorized: false 现在是 skipSslCertificateValidation: true
  • 根据 content-type 标头使用 body 来澄清负载。
  • resolveWithFullResponse 现在是 returnFullResponse 并具有类似的行为