【问题标题】:Amazon Gateway API with Lambda - Could not parse request body into json带有 Lambda 的 Amazon Gateway API - 无法将请求正文解析为 json
【发布时间】:2016-02-07 14:15:57
【问题描述】:

例如,我似乎遇到了 Amazon Gateway API 不喜欢我发送的参数的问题。

$.ajax({
        url: "https://tibqwxuqoh.execute-api.us-east-1.amazonaws.com/dev/getitems",
        type: "POST",
        data: {
            "device": "test",
            "datetime": "1446757400919"
        },
        success: function (returnhtml) {
            console.log(returnhtml);
            $("#result").append("DOES NOT WORK - <br>" + JSON.stringify(returnhtml));
        }
    });

    $.ajax({
        url: "https://tibqwxuqoh.execute-api.us-east-1.amazonaws.com/dev/getitems",
        type: "POST",
        data: {},
        success: function (returnhtml) {
            console.log(returnhtml);
            $("#result").append("<br>WORKS ???? - <br>" + JSON.stringify(returnhtml));
        }
    });

这是一个工作示例。 http://jsfiddle.net/Uwcuz/4315/

有人可以告诉我为什么每次我添加参数时它都不会让我发送参数我得到这个错误。

{
    Type = User;
    message = "Could not parse request body into json.";
} 

这行得通,但我觉得有点奇怪。

$.ajax({
        url: "https://tibqwxuqoh.execute-api.us-east-1.amazonaws.com/dev/getitems",
        type: "POST",
        data: "{\"device\": \"test\",\"datetime\": \"1446757444524\"}",
        success: function (returnhtml) {
            console.log(returnhtml);
            $("#result").append("WORKS - <br>" + JSON.stringify(returnhtml));
        }
    });

【问题讨论】:

    标签: api amazon-web-services aws-lambda


    【解决方案1】:

    问题在于您如何将数据发送到 API Gateway。 在不知道您的 API 配置的详细信息的情况下,我猜您有一个应用程序/json 的请求映射设置。 默认情况下,jQuery 会将您的数据作为 application/x-www-form-urlencoded 发布,但您希望将其作为 json 发送。

    您可以做到这一点,而不必自己过多地摆弄数据:

    var requestParams = {
        url: "https://tibqwxuqoh.execute-api.us-east-1.amazonaws.com/dev/getitems",
        method: "POST,
        contentType: "application/json",
        dataType: "json",
        data: JSON.stringify({
            "device": "test",
            "datetime": "1446757400919"
        });
    };
    var request = $.ajax(requestParams);
    

    这里的关键是 JSON.stringify() 并告诉 jQuery dataType 是 json 以及将 contentType 设置为 application/json。

    【讨论】:

      猜你喜欢
      • 2018-12-01
      • 2021-01-16
      • 2016-01-30
      • 2020-04-16
      • 2017-11-30
      • 1970-01-01
      • 2016-07-12
      • 2016-12-14
      • 1970-01-01
      相关资源
      最近更新 更多