You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

将Zapier原生JS POST请求迁移至NestJS是否正确?

迁移Zapier POST请求到NestJS的代码修正

你的代码存在几个关键问题,下面逐一说明并给出修正后的版本:

问题点分析

  • HttpService.post参数顺序错误:NestJS的httpService.post方法签名为post(url: string, body?: any, options?: AxiosRequestConfig),你把包含headers和body的配置对象作为第二个参数传入,会导致请求体被错误设置为配置对象,而非实际要发送的数据。
  • 手动JSON序列化冗余:HttpService会自动将JavaScript对象序列化为JSON(只要Content-Type设置为application/json),无需手动调用JSON.stringify。
  • toPromise()已废弃:RxJS的toPromise()方法已被废弃,推荐使用lastValueFrom将Observable转换为Promise。
  • 字段名称不匹配:原Zapier代码中phone字段对应inputData.caller_number,但你的代码中使用了incomingData.number,需确认传入的incomingData是否包含正确字段名,否则会导致数据错误。

修正后的代码

import { lastValueFrom } from 'rxjs';

async postCallerInfoAndSetCallTransfers(incomingData) {
  const data = {
    api_token: incomingData.api_token,
    call_type: 'Inbound',
    data: {
      zip: incomingData.zip,
      phone: incomingData.caller_number, // 修正:与原代码保持一致,需确认incomingData包含该字段
    },
    placement_id: incomingData.placement_id,
    sub_3: incomingData.uuid,
    version: 17,
  };

  const requestOptions = {
    headers: {
      'Content-Type': 'application/json',
    },
  };

  // 使用lastValueFrom替代废弃的toPromise()
  const response = await lastValueFrom(
    this.httpService.post('URL', data, requestOptions)
  );

  // 可根据需求返回响应数据或处理结果
  return response.data;
}

补充说明

  • 确保已在模块中导入HttpModule并将HttpService注入到服务类中。
  • 建议添加try/catch错误处理逻辑,避免未处理的Promise rejection。
  • 若API有特殊要求必须手动序列化JSON,可将data替换为JSON.stringify(data),但通常无需额外操作。

内容的提问来源于stack exchange,提问作者user17281101

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 03:55:25