node.js - 获取语​​法错误 : Unexpected token u in JSON at position 0 when running Lambda Test

标签 node.js amazon-web-services aws-lambda

使用

运行 Lambda 测试
{
  "var1": "2017-04-17T18:48:03.608Z",
  "var2": "0.45",
  "var3": "0.5"
}

功能:

exports.handler =  (event, context, callback) => {

    console.log("event.body = " + event.body);
    const {var1, var2, var3} = JSON.parse(event.body);
    const tmpItem = {
        "var_1": var1,
        "var_2": var2,
        "var_3": var3
    };
    console.log('Inserting item');
}

给出以下异常:

请求编号: “3aa87175-d544-11e8-ab0a-2b268a563fb1”

函数日志:

START RequestId: 3aa87175-d544-11e8-ab0a-2b268a563fb1 Version: $LATEST
2018-10-21T15:16:05.617Z    3aa87175-d544-11e8-ab0a-2b268a563fb1    event.body = undefined
2018-10-21T15:16:05.636Z    3aa87175-d544-11e8-ab0a-2b268a563fb1    SyntaxError: Unexpected token u in JSON at position 0
    at JSON.parse (<anonymous>)
    at exports.handler (/var/task/index.js:18:89)
END RequestId: 3aa87175-d544-11e8-ab0a-2b268a563fb1
REPORT RequestId: 3aa87175-d544-11e8-ab0a-2b268a563fb1  Duration: 82.98 ms  Billed Duration: 100 ms     Memory Size: 128 MB Max Memory Used: 25 MB  
RequestId: 3aa87175-d544-11e8-ab0a-2b268a563fb1 Process exited before completing request

似乎是什么问题?

最佳答案

这是因为当你用数据包测试你的 lambda 时,比如说

{
  "var1": "2017-04-17T18:48:03.608Z",
  "var2": "0.45",
  "var3": "0.5"
}

然后该数据包作为事件传递给处理程序。

但是,你正在做 JSON.parse(event.body),但是对于上面的数据包,event.bodyundefined(在位置 0 处有标记 u

您应该将测试包更改为:

{
    "body": "{\"var1\":\"2017-04-17T18:48:03.608Z\",\"var2\":\"0.45\",\"var3\":\"0.5\"}"
}

请注意,正文是字符串化的 JSON,因为 API Gateway Lambdas 需要字符串化格式的事件正文。

关于node.js - 获取语​​法错误 : Unexpected token u in JSON at position 0 when running Lambda Test,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52914537/

相关文章:

amazon-web-services - 提供的证书不是有效的自签名证书。请提供有效的自签名证书或证书链

amazon-web-services - 从 API 网关测试调用 lambda,但命中端点不会调用 lambda。 500 退回

python - 全局包安装在哪里以及它们如何在 Python 和 Node 中执行?

node.js - 错误: Cannot find module 'connect-multiparty'

amazon-web-services - AWS SSM session 管理器不显示实例

amazon-web-services - AWS CDK S3 部署错误 - 上传的文件必须是非空 zip

javascript - 父类(super class)化stream.Duplex的问题

node.js - 应用程序引擎部署 [13] 处理用户代码时出错

amazon-web-services - AWS Lambda 存储上次运行时间吗?

python - Lambda 错误 : no module found. Cryptography.hamtaz.bindings._constant_time