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 载荷,使用 buffer 上传文件,使用 FormData 实例处理 multipart/form-data,使用 URLSearchParams 处理 application/x-www-form-urlencoded
  • headers: 键值对形式。
    • 如果 bodyFormData 实例,n8n 会自动添加 content-type: multipart/form-data
    • 如果 bodyURLSearchParams 实例,n8n 会自动添加 content-type: application/x-www-form-urlencoded
    • 要覆盖此行为,可以手动设置 content-type 头。
  • arrayFormat: 如果查询字符串包含数组数据(如 const qs = {IDs: [15,17]}),该值定义 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: 用于 Basic 认证。提供 usernamepassword。n8n 建议省略此项,改用 helpers.httpRequestWithAuthentication(...)
  • disableFollowRedirect: 默认情况下 n8n 会跟随重定向。设为 true 可禁用此行为。
  • skipSslCertificateValidation: 用于调用没有正确证书的 HTTPS 服务
  • returnFullResponse: 不仅返回响应体,还会返回包含更多数据的对象,格式为:{body: body, headers: object, statusCode: 200, statusMessage: 'OK'}
  • encoding: n8n 可以自动检测内容类型,但你可以指定 arrayBuffer 来获取可读取和交互的 Buffer。

示例#

如需查看示例,请参考 Mattermost 节点

旧版 helper 的弃用#

之前使用 this.helpers.request(options) 的 helper 实现依赖并暴露了 request-promise 库。该实现在版本 1 中已被移除。

为最大限度减少兼容性问题,n8n 已将其透明地转换为了另一个名为 Axios 的库。

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

新版 helper 迁移指南#

新版 helper 更加健壮、不依赖特定库且更易使用。

所有新节点都应使用新版 helper。强烈建议将现有自定义节点迁移至新版 helper。以下是迁移时的主要注意事项:

  • 接受 url 参数,不再接受 uri 参数
  • encoding: null 现在必须改为 encoding: arrayBuffer
  • rejectUnauthorized: false 现在应改为 skipSslCertificateValidation: true
  • 根据 content-type 头正确使用 body 来明确负载内容
  • resolveWithFullResponse 现已改为 returnFullResponse,功能类似