首页 > 解决方案 > 调用 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.jsamazon-web-serviceslambdaamazon-cognito

解决方案


使用建议的 Node 8 方法,async/await您应该使用以下方法来构建函数:

async function handler(event) {
  const response = doSomethingAndReturnAJavascriptObject();
  return response;
}

您收到该错误是因为您返回的任何内容都不能被解析为 JSON 对象。

如果没有看到您的代码,就很难进一步调试。我希望您可能不小心没有使用dynamo/cognito API 调用await.promise()版本,这会导致您返回 Promise 而不是结果。

callback()注意,如果您发现它更容易,您仍然可以在 Node 8中使用“旧”方法。


推荐阅读