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

升级Node.js 18后,Lambda中UpdateRestApiCommand使用报错求助

解决Node.js 18下AWS SDK v3 UpdateRestApiCommand的TypeError问题

问题根源

你遇到的TypeError: (intermediate value).on is not a function是因为AWS SDK v3和v2的API设计完全不同:

  • 旧代码用的是SDK v2,apigateway.updateRestApi(params)返回的是带事件监听能力的请求对象,支持.on()绑定回调;
  • 新代码里的UpdateRestApiCommand是SDK v3的命令对象,它只是封装了请求参数,本身没有.on()和.send()方法,必须通过APIGatewayClient实例的.send()方法执行,且该方法返回Promise,而非事件驱动的请求对象。

修正后的代码实现

1. 先导入正确的SDK v3模块

// ES模块语法
import { APIGatewayClient, UpdateRestApiCommand } from "@aws-sdk/client-api-gateway";

// 或者CommonJS语法(Lambda默认支持)
// const { APIGatewayClient, UpdateRestApiCommand } = require("@aws-sdk/client-api-gateway");

2. 创建API网关客户端实例

const apiGatewayClient = new APIGatewayClient({ 
  region: "你的AWS区域(如us-east-1)" 
});

3. Async/Await风格实现(推荐)

对应原代码的success/error/complete逻辑:

exports.handler = async (event) => {
  // 定义UpdateRestApi参数
  const params = {
    restApiId: "你的RestAPI ID",
    patchOperations: [
      // 示例:修改API名称
      {
        op: "replace",
        path: "/name",
        value: "UpdatedAPI"
      }
    ]
  };

  try {
    const command = new UpdateRestApiCommand(params);
    const response = await apiGatewayClient.send(command);
    
    console.log("Success!");
    return {
      statusCode: 200,
      body: JSON.stringify(response.data)
    };
  } catch (error) {
    console.log("Error!");
    return {
      statusCode: 500,
      body: JSON.stringify(error)
    };
  } finally {
    console.log("Done!"); // 对应原complete事件
  }
};

4. Promise链式调用风格实现(贴近原事件监听逻辑)

如果习惯链式写法,可用then/catch/finally替代事件监听:

exports.handler = (event) => {
  return new Promise((resolve, reject) => {
    const params = {
      restApiId: "你的RestAPI ID",
      patchOperations: [] // 你的更新操作
    };

    const command = new UpdateRestApiCommand(params);
    apiGatewayClient.send(command)
      .then(response => {
        console.log("Success!");
        resolve({
          statusCode: 200,
          body: JSON.stringify(response.data)
        });
      })
      .catch(error => {
        console.log("Error!");
        reject({
          statusCode: 500,
          body: JSON.stringify(error)
        });
      })
      .finally(() => {
        console.log("Done!");
      });
  });
};

注意事项

  • 确保Lambda环境已安装@aws-sdk/client-api-gateway包,若用层或本地打包,需包含该依赖;
  • Node.js 18环境下AWS官方推荐使用SDK v3,v2版本已进入维护阶段,不再添加新特性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 01:50:28