0

我的 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。

4

1 回答 1

2

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

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",
          }),
        };
      });
  });
};
于 2021-10-16T21:10:34.637 回答