【问题标题】:Node JS AWS Serverless 502 HTTP/1.1 502 Bad Gateway节点 JS AWS 无服务器 502 HTTP/1.1 502 网关错误
【发布时间】:2021-10-17 11:18:22
【问题描述】:

我的 lambda 函数有一个 502 Bad gateway 响应,我在 MongoDB atlas 数据库上创建数据条目并返回创建的条目。

我的代码如下,

handler.js 函数入口点

module.exports.category_create = async (event) => {
  return category.createCategory(event);
};

category.js 函数

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

此 API 在 DB 上创建必要的数据,但 API 响应如下,

HTTP/1.1 502 Bad Gateway
content-type: application/json; charset=utf-8
vary: origin
access-control-allow-credentials: true
access-control-expose-headers: WWW-Authenticate,Server-Authorization
cache-control: no-cache
content-length: 0
Date: Sat, 16 Oct 2021 19:14:33 GMT
Connection: close

似乎 API 没有等到返回有效响应。在调用 connectToDatabase() 之前我也使用了 await。

【问题讨论】:

    标签: node.js amazon-web-services rest aws-lambda


    【解决方案1】:

    你只需要回报你的承诺。像这样,

    module.exports.createCategory = async (event) => {
     return 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 {
              body: JSON.stringify({
                statusCode: err.statusCode || 500,
                message: "Could not create a category",
              }),
            };
          });
      });
    };
    

    【讨论】:

    • 谢谢@LawrenceCherone。我现在已经更新了。
    • 谢谢,我已经更新了
    猜你喜欢
    • 2019-06-07
    • 2016-07-29
    • 2015-09-25
    • 1970-01-01
    • 2014-01-25
    • 2016-07-02
    • 1970-01-01
    • 2019-09-20
    • 1970-01-01
    相关资源
    最近更新 更多