面向节点构建者的 HTTP 请求辅助工具#
n8n 提供灵活的 HTTP 请求辅助工具,可抽象化大部分复杂性。
仅限编程式风格
本文档中的信息适用于使用编程式风格构建节点,不适用于声明式风格节点。
使用方法#
在 execute 函数内调用该辅助工具。
// 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 是一个对象:
{
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:键值对组合。- 若
body为 FormData 实例,n8n 会自动添加content-type: multipart/form-data。 - 若
body为 URLSearchParams 实例,n8n 会自动添加content-type: application/x-www-form-urlencoded。 - 如需覆盖此行为,请手动设置
content-type请求头。
- 若
arrayFormat:当查询字符串包含数组数据时(例如const qs = {IDs: [15,17]}),该参数定义数组的格式化方式:indices(默认值):{ a: ['b', 'c'] }格式化为a[0]=b&a[1]=cbrackets:{ a: ['b', 'c'] }格式化为a[]=b&a[]=crepeat:{ a: ['b', 'c'] }格式化为a=b&a=ccomma:{ a: ['b', 'c'] }格式化为a=b,c
auth:用于基础认证,需提供username和password。n8n 建议省略此参数,改用helpers.httpRequestWithAuthentication(...)。disableFollowRedirect:默认情况下 n8n 会跟随重定向,设为 true 可禁用此功能。skipSslCertificateValidation:用于调用未配置有效证书的 HTTPS 服务。returnFullResponse:设为 true 时返回包含完整响应信息的对象{body: body, headers: object, statusCode: 200, statusMessage: 'OK'},而非仅返回响应体。encoding:n8n 可自动检测内容类型,也可指定arrayBuffer来获取可读写的 Buffer。
示例#
具体示例请参考 Mattermost 节点。
旧版辅助函数的弃用#
旧版辅助函数 this.helpers.request(options) 基于 request-promise 库实现,该库在版本 1 中已被移除。
为最大限度保证兼容性,n8n 已将其透明迁移至 Axios 库。
新版辅助函数迁移指南#
新版辅助函数具有更强的鲁棒性、库无关性且更易使用。
新节点应全部使用新版辅助函数,强烈建议将现有自定义节点迁移至新版本。迁移时需重点关注以下变化:
- 仅接受
url参数,不再接受uri encoding: null需改为encoding: arrayBufferrejectUnauthorized: false需改为skipSslCertificateValidation: true- 根据
content-type请求头规范使用body传输载荷 resolveWithFullResponse改为returnFullResponse,功能保持一致