node.js - 调用 Node 8.10 Lambda 时 JSON 无效
问题描述
成功登录后,我正在使用 lambda 和 cognito 写入 dynamoDB。
Node 8.10 的布局与 promise 和asycn/await
. 回报对callback(null, event)
我不起作用。现在任何人都如何解决Invalid lambda function output : Invalid JSON
节点 8.10 的问题。
// Load the AWS SDK for Node.js
var AWS = require('aws-sdk');
// Set the region
//AWS.config.update({region: 'REGION'});
// Create DynamoDB document client
var docClient = new AWS.DynamoDB.DocumentClient({apiVersion: '2012-08-10'});
exports.myHandler = async (event, context, callback) => {
// TODO implement
console.log ("Authentication successful");
console.log ("Trigger function =", event.triggerSource);
console.log ("User pool = ", event.userPoolId);
console.log ("App client ID = ", event.callerContext.clientId);
console.log ("User ID = ", event.userName);
const params = {
TableName: 'xxxx',
Item: {
'userId': event.userName,
'systemUpdateDate': new Date().toJSON()
}
};
let putItem = new Promise((res, rej) => {
docClient.put(params, function(err, data) {
if (err) {
console.log("Error", err);
} else {
console.log("Success", data);
}
});
});
const result = await putItem;
console.log(result);
// Return to Amazon Cognito
callback(null, event);
};
谢谢
解决方案
使用建议的 Node 8 方法,async/await
您应该使用以下方法来构建函数:
async function handler(event) {
const response = doSomethingAndReturnAJavascriptObject();
return response;
}
您收到该错误是因为您返回的任何内容都不能被解析为 JSON 对象。
如果没有看到您的代码,就很难进一步调试。我希望您可能不小心没有使用dynamo/cognito API 调用await
的.promise()
版本,这会导致您返回 Promise 而不是结果。
callback()
注意,如果您发现它更容易,您仍然可以在 Node 8中使用“旧”方法。
推荐阅读
- java - Gradle 项目同步失败
- sql - Oracle SQL Developer - 插入输出错误时,顺序触发器仍然递增
- swift - 由于 URLQueryItems 的顺序,单元测试一直失败
- vuejs2 - 如何使用带有 chart-js 的 Vue 组件制作动态图表
- php - 获取数组结果然后与数据库配对
- c++ - 如何在我的 C++ 代码中获得运行时的双重免费错误
- python - 在 python 的 [] 中使用 break 或 continue 会出错
- sql - 尝试使用 Openrecordset 结果时出现运行时错误 438
- javascript - 使用字符串和对象名称在 javascript 中运行函数
- javascript - 添加类其他部分后自动输入文本完成时显示文本