无法将请求主体解析为json:无法识别的令牌

时间:2017-07-29 06:17:08

标签: ajax aws-api-gateway

我有一个非常简单的AJAX代码,它调用AWS API网关端点:

$.ajax({
        url: 'https://omitted.execute-api.ap-southeast-2.amazonaws.com/test/rec',
        type: 'post',
        data: {
            'zipcode': '1234',
            'url': 'www.google.com'
        },
        dataType: 'json',
        success: function (data) {
            console.info(data);
        }
    });

我得到的是:

  

无法将请求正文解析为json:无法识别的令牌' zipcode':期待(' true',' false'或' null&#39 ;)`

数据应该是JSON格式,所以我做错了什么?

我也尝试过:

$.post('https://omitted.execute-api.ap-southeast-2.amazonaws.com/test/rec',
    {
        'zipcode': '1234',
        'url': 'www.google.com'
    }, 
    function(data, textStatus) {
      //data contains the JSON object
      //textStatus contains the status: success, error, etc
}, "json");

$.post('https://omitted.execute-api.ap-southeast-2.amazonaws.com/test/rec',
    'zipcode=1234&url=www.google.com', 
    function(data, textStatus) {
      //data contains the JSON object
      //textStatus contains the status: success, error, etc
}, "json");

他们正在返回相同的结果。

5 个答案:

答案 0 :(得分:1)

修正了它:

$.postJSON = function(url, data, callback) {
    return jQuery.ajax({
    headers: { 
        'Accept': 'application/json',
        'Content-Type': 'application/json' 
    },
    'type': 'POST',
    'url': url,
    'data': JSON.stringify(data),
    'dataType': 'json',
    'success': callback
    });
};

答案 1 :(得分:0)

请删除'从关键词:

data: {
        zipcode: '1234',
        url: 'www.google.com'
    },

答案 2 :(得分:0)

这通常是来自AWS Lambda的问题,以及您如何设置API网关。你的代码看起来很好。我会检查你如何在API网关上设置集成。

我会检查您在APIGateway上的集成设置,以确保您有类似的内容:

{"body-json" : $input.json('$')}

在模板映射中处理JSON。

答案 3 :(得分:0)

您的客户端代码非常好,问题在于端点实现,服务器无法解析json。

答案 4 :(得分:0)

我将集成请求更改为代理集成(在API GW中选择方法,转到集成请求窗口,然后选择“使用Lambda代理集成”),并且可以使用!