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

AWS Serverless Lambda对接MongoDB Atlas返回502 Bad Gateway问题咨询

问题根本原因

你的createCategory异步函数没有正确返回内层数据库操作的异步结果,Lambda执行到函数末尾时,还未等待CategoryModel.create执行完成就返回了undefined,API Gateway无法解析空返回值,因此抛出502 Bad Gateway错误。

具体问题点
  • 你仅为connectToDatabase添加了await,但没有返回then回调内部的CategoryModel.create Promise对象,所以await只会等待数据库连接完成,不会等待数据写入和返回逻辑执行,函数提前结束,返回值为空。
  • 错误分支的返回值没有将statusCode放在顶层字段,不符合API Gateway要求的Lambda响应格式,即使走到错误分支也会触发502错误。
修复方案

推荐使用async/await写法替换嵌套then链式调用,逻辑更清晰,避免Promise回调嵌套遗漏return的问题:

module.exports.createCategory = async (event) => {
  try {
    await connectToDatabase();
    const category = await CategoryModel.create(JSON.parse(event.body));
    console.log(`Category creation success ${category}`);
    return {
      statusCode: 200,
      body: JSON.stringify(category)
    };
  } catch (err) {
    return {
      statusCode: err.statusCode || 500,
      body: JSON.stringify({
        message: "Could not create a category"
      })
    };
  }
};

如果要保留原有的then链式写法,需要补充两层return,确保外层await可以等待整个异步流程执行完成:

module.exports.createCategory = async (event) => {
  return await connectToDatabase().then(() => {
    return CategoryModel.create(JSON.parse(event.body))
      .then((category) => {
        console.log(`Category creation success ${category}`);
        return {
          statusCode: 200,
          body: JSON.stringify(category),
        };
      })
      .catch((err) => {
        return {
          statusCode: err.statusCode || 500,
          body: JSON.stringify({
            message: "Could not create a category",
          }),
        };
      });
  });
};
验证步骤
  • 部署修改后的代码后调用接口,确认返回结构中statusCode为顶层字段,未嵌套在body内
  • 前往AWS Lambda控制台查看函数执行日志,确认函数返回值为预期的响应对象,而非null/undefined

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 15:48:03