跳至内容

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

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

仅限编程风格

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

用法#

execute函数内部调用helper。

1
2
3
4
5
6
7
8
9
// If no auth needed
const response = await this.helpers.httpRequest(options);

// If auth needed
const response = await this.helpers.httpRequestWithAuthentication.call(
	this, 
	'credentialTypeName', // For example: 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: a key-value pair.
    • 如果 bodyFormData 的实例,那么 n8n 会自动添加 content-type: multipart/form-data
    • 如果 bodyURLSearchParams 的实例,那么 n8n 会添加 content-type: application/x-www-form-urlencoded
    • 要覆盖此行为,请设置一个content-type头。
  • arrayFormat: if your query string contains an array of data, such as const qs = {IDs: [15,17]}, the value of arrayFormat defines how n8n formats it.
    • 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来接收一个可读取和交互的Buffer。

示例#

例如,请参考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,功能类似
优云智算