Home > Blockchain >  Node JS AWS Serverless 502 HTTP/1.1 502 Bad Gateway
Node JS AWS Serverless 502 HTTP/1.1 502 Bad Gateway

Time:10-18

There is a 502 Bad gateway response with my lambda function where I create data entry on MongoDB atlas database and return created entry.

My code as follows,

handler.js function entry point

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

category.js function

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,

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. I've used await before calling connectToDatabase() as well.

CodePudding user response:

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