AWS API 网关 - CORS + POST 不起作用 [英] AWS API Gateway - CORS + POST not working

查看:34
本文介绍了AWS API 网关 - CORS + POST 不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

CORS 真的让我发疯了,我真的没有任何想法可以让它发挥作用.

CORS is really driving me crazy and I'm really out of ideas as of what to try to make it work.

我创建了一个简单的 APIG Api,其中包含 1 个名为abc"的资源,并添加了 2 个方法 GETPOST,其中 Authorization 设置为NONEAPI Key Required 设置为 false,一切都部署到一个名为dev"的阶段.

I have created a simple APIG Api with 1 resource called 'abc' and added 2 methods GET and POST both with Authorization set to NONE and API Key Required set to false, everything deployed to a stage called 'dev'.

当然,我在这两种方法上都启用了 CORS,我看到了 3 个标头 Access-Control-Allow-OriginAccess-Control-Allow-HeadersAccess-Control-Allow-Methods 添加到 OPTIONS 方法,Access-Control-Allow-Origin 添加到 POSTGET 方法.

Of course I enabled CORS on both methods and I see the 3 headers Access-Control-Allow-Origin, Access-Control-Allow-Headers and Access-Control-Allow-Methods added to the OPTIONS method and the Access-Control-Allow-Origin added to the POST and GET methods.

两个调用都映射到同一个 lambda 函数,该函数只是将Hello from Lambda"文本输出到控制台.

Both calls are mapped to the same lambda function that simply outputs a 'Hello from Lambda' text to the console.

然后我创建了一个简单的 html 页面,我在 S3 上作为 静态网站 托管,使用 Route53 将域指向它并开始使用 jQuery $.ajax 测试 API 以进行调用.

Then I have created a simple html page I hosted as a static website on S3, pointed a domain to it using Route53 and started testing the API using jQuery $.ajax to make the calls.

所有看起来都很简单、直接并且完全按照文档中的说明进行,除了只有 GET 可以正常工作并按预期将文本输出到控制台.POST 版本导致以下错误:

All seems easy, straightforward and exactly as explained in the docs, except only the GET works and outputs the text to the console as expected. The POST version results in the following error:

请求的资源上不存在Access-Control-Allow-Origin"标头.因此不允许访问源http://example.com".响应的 HTTP 状态代码为 400.

预检调用有效并返回 200 OK 并且所有标头都在那里,但 POST 调用返回该错误和 400 Bad Request.

The preflight call works and returns 200 OK and all headers are there, but the POST call returns that error and a 400 Bad Request.

非常感谢任何帮助,我希望 AWS 团队也关注...

Please any help is really appreciated, I hope the AWS team is watching too...

谢谢各位.

已编辑 - 从 Google Chrome 复制:

EDITED - Copied from Google Chrome:

POST 原始请求标头:

POST Raw Request Headers:

POST /dev/urls HTTP/1.1
Host: kykul1mshe.execute-api.us-east-1.amazonaws.com
Connection: keep-alive
Content-Length: 73
Accept: application/json, text/javascript, */*; q=0.01
Origin: http://example.com
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36
Content-Type: application/json
Referer: http://example.com/dev.html
Accept-Encoding: gzip, deflate, br
Accept-Language: fr-FR,fr;q=0.8,en-US;q=0.6,en;q=0.4

POST 原始响应头:

POST Raw Response Headers:

HTTP/1.1 400 Bad Request
Date: Fri, 19 Aug 2016 02:14:16 GMT
Content-Type: application/json
Content-Length: 177
Connection: keep-alive
x-amzn-RequestId: a1160e45-65b2-11e6-9766-cd61e49fbcdb
X-Cache: Error from cloudfront
Via: 1.1 d64756b4df47ce24d6c62b5a8de97e87.cloudfront.net (CloudFront)
X-Amz-Cf-Id: N9mf7apicKbSM_MiZjePbEgZGIFKckWJ3lZljH8iHVKFVTcIIOQuHg==

这将返回 400 Bad Request

This returns 400 Bad Request

OPTIONS 原始请求标头:

OPTIONS Raw Request Headers:

Accept:*/*
Accept-Encoding:gzip, deflate, sdch, br
Accept-Language:fr-FR,fr;q=0.8,en-US;q=0.6,en;q=0.4
Access-Control-Request-Headers:accept, content-type
Access-Control-Request-Method:POST
Connection:keep-alive
Host:kykul1mshe.execute-api.us-east-1.amazonaws.com
Origin:http://example.com
Referer:http://example.com/dev.html
User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36

OPTIONS 原始响应标头:

OPTIONS Raw Response Headers:

Access-Control-Allow-Headers:Content-Type,X-Amz-Date,Authorization,X-Api-Key,Cache-Control,X-Requested-With
Access-Control-Allow-Methods:POST,OPTIONS
Access-Control-Allow-Origin:*
Connection:keep-alive
Content-Length:79
Content-Type:application/json
Date:Fri, 19 Aug 2016 02:14:16 GMT
Via:1.1 d64756b4df47ce24d6c62b5a8de97e87.cloudfront.net (CloudFront)
X-Amz-Cf-Id:KpGEDmIuf5RHcUnBWuA3oEMZgWHwrjy3SpLuOflRhAD8IIx5vyKGSw==
x-amzn-RequestId:a10bae11-65b2-11e6-bcf7-63b49c24629e
X-Cache:Miss from cloudfront

返回 200 OK

推荐答案

好的,我找到了问题的根源,恰好与 APIG 完全无关,并确认了@AbhignaNagaraja 提到的,我的 APIG 配置正确.

Ok, I found the origin of the problem, which happens to be totally unrelated to APIG, and confirms what @AbhignaNagaraja mentioned, that my APIG was properly configured.

问题实际上出在我调用 jQuery.ajax 的方式上,我认为当 contentType 为application/json"时,我认为它足够聪明,可以将我的参数转换为 JSON 字符串.似乎我必须手动对 JSON 参数进行字符串化,而不是传递 JSON 并让 jQuery 对其进行字符串化.

所以这是一个糟糕的电话:

So this is the bad call:

$.ajax({
        url: myEndpoint,
        type: 'POST',
        crossDomain: true,
        data: {
            url: $('#url').val()
        },
        headers: {
            "X-Api-Key": 'blablabla'
        },
        dataType: 'json',
        contentType: "application/json",
        success: function (data) {
            console.info(data);
        }
    });

这是正确的调用:

 $.ajax({
        url: myEndpoint,
        type: 'POST',
        crossDomain: true,
        data: JSON.stringify({
            url: $('#url').val()
        }),
        headers: {
            "X-Api-Key": 'blablabla'
        },
        dataType: 'json',
        contentType: "application/json",
        success: function (data) {
            console.info(data);
        }
    });

如果您正在使用 CORS 调试此类问题,这可能是一个提示:只需下载 AWS APIG SDK 并尝试使用 AWS 提供的 apigClient 执行调用,并将标头与您通过自定义客户端获得的标头进行比较.在检查我使用 jQueryapigClient 获得的 2 组标头时,我注意到请求有效负载看起来不同,这就是我意识到格式错误的原因,然后是 400 代码没有'Access-Control-Allow-Origin'标头都是有意义的.

This can be a hint if you are debugging such an issue with CORS: just download the AWS APIG SDK and try executing the call using the apigClient provided by AWS and compare headers with the ones you get with your custom client. When examining the 2 sets of headers I got with jQuery and apigClient, I noticed the Request Payload looked different and thats how I realized the format was wrong, then the 400 code and the No 'Access-Control-Allow-Origin' header is present all made sense.

我希望这会有所帮助.

这篇关于AWS API 网关 - CORS + POST 不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆