ajax - 无法将请求正文解析为 json : Unrecognized token

标签 ajax aws-api-gateway

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

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

我要回来的是:

Could not parse request body into json: Unrecognized token 'zipcode': was expecting ('true', 'false' or 'null')`



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

关于ajax - 无法将请求正文解析为 json : Unrecognized token,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45386003/

相关文章:

javascript - 使用 json 和 Ajax 将对象传递给 MVC View

javascript - 如何防止此ajax请求丢失数据

amazon-web-services - 取消选中 'use lambda proxy integration' cloudformation

amazon-web-services - AWS API Gateway 不能有多个路径?

amazon-web-services - 如何使用 YAML CloudFormation 模板在 API Gateway V2 资源上添加标签

amazon-web-services - 公共(public) Route53 CNAME 记录到私有(private) API 网关

javascript - rails 5 : render partial in another partial with AJAX

javascript - 如何进一步过滤搜索步骤的结果?

amazon-web-services - 如何在 AWS API Gateway 响应模板中使用 Velocity 变量?

javascript - 使用 jQuery 更新图像源