繁体   English   中英

无法将请求正文解析为 json:无法识别的令牌

[英]Could not parse request body into json: Unrecognized token

我有一个非常简单的 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:无法识别的令牌“邮政编码”:期待(“真”、“假”或“空”)`

数据应该是 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");

他们返回相同的结果。

修复它:

$.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
    });
};

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

请从密钥中删除 ',例如:

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

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

我会检查你在 APIGateway 上的集成设置,以确保你有类似的东西:

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

在您的模板映射中处理 JSON。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM