我的 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。
uj5u.com熱心網友回復:
你只需要回報你的承諾。像這樣,
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",
}),
};
});
});
};
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/328441.html
標籤:节点.js 亚马逊网络服务 休息 aws-lambda
