首页 文章

AWS API Gateway - 调用API方法时出错 - 'Could not parse request body into json'

提问于
浏览
2

我有一个简单的POST方法连接到我的AWS API Gateway中的lambda函数 .

当我执行测试时(通过Gateway API控制台)一切正常,测试得到我正在寻找的结果 . 它的简单 - 发布一个JSON,得到一个JSON .

但是,在部署API然后发送测试中使用的相同JSON(通过http post)后,我得到 'Could not parse request body into json' .

有谁知道我可能做错了什么?注意:我不打算使用模型,我只想传递JSON . 我相信当亚马逊写“输入直通”之类的东西时,他们意味着输入可以传递给lambda函数 .

以下是我的AWS Gateway API设置的图像:

METHOD REQUEST:
enter image description here

INTEGRATION REQUEST:
enter image description here

METHOD RESPONSE:
enter image description here

INTEGRATION RESPONSE:
enter image description here

2 回答

  • 0

    以字符串格式设置参数(没有json和没有数组):

    我在curl执行中使用了http_build_query()函数:

    $curl = curl_init();
    
            curl_setopt_array($curl, array(
                CURLOPT_RETURNTRANSFER => 1,
                CURLOPT_URL => "https://your_url_here",
                CURLOPT_POST => 1,
                CURLOPT_SSL_VERIFYHOST => 0,
                CURLOPT_SSL_VERIFYPEER => 0,
                CURLOPT_POSTFIELDS => http_build_query(array(
                    "key1" => "val1",
                    "key2" => "val2",
                ))
            ));
    
            $resp = curl_exec($curl);
            print_r($resp);
            if (!curl_exec($curl)) {
                die('Error: "' . curl_error($curl) . '" - Code: ' . curl_errno($curl));
            }
            curl_close($curl);
    
  • 5

    我找到了解决方案 . 问题是在POST请求中你需要将你的身体作为字符串而不是JSON对象发送,并且该字符串需要格式化正确

    即'{“key1”:“val1”,“key2”:22,“key3”:15,“key4”:“val4”}'

    像这样:

    function post() {
    
    
    $.ajax({
        url: "https://myapi.us-east-1.amazonaws.com/myStage/myPath",
        type: "POST",
        data: '{"key1": "val1","key2": 22,"key3": 15,"key4": "val4"}',
        mozSystem: true,
        dataType: "text", //set to"json" usually
        success: function (result) {
            switch (result) {
                case true:
                    processResponse(result);
                    break;
                default:
                    resultDiv.html(result);
            }
        },
        error: function (xhr, ajaxOptions, thrownError) {
            alert('error ' + xhr.status + ' ' + thrownError);
            alert(thrownError);
        }
     });
    
    
    };
    

相关问题