简体   繁体   English

节点 JS AWS 无服务器 502 HTTP/1.1 502 错误网关

[英]Node JS AWS Serverless 502 HTTP/1.1 502 Bad Gateway

There is a 502 Bad gateway response with my lambda function where I create data entry on MongoDB atlas database and return created entry.我的 lambda 函数有一个 502 Bad gateway 响应,我在 MongoDB atlas 数据库上创建数据条目并返回创建的条目。

My code as follows,我的代码如下,

handler.js function entry point handler.js 函数入口点

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

category.js function 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",
          }),
        };
      });
  });
};

This API creates the necessary data on DB, But API response is as below,此 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

Seems the API is not waiting until a valid response is getting returned.似乎 API 不会等到返回有效响应。 I've used await before calling connectToDatabase() as well.我在调用 connectToDatabase() 之前也使用了 await。

You only need to return your promise.你只需要回报你的承诺。 Like this,像这样,

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",
          }),
        };
      });
  });
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM