我有一个工作的AWS lambda(部署和运行),通过API网关提供HTTPS响应,我现在正试图将其合并到一个html页面中。但是ajax对于这个URL仍然失败(例如,对于本地文件可以正常工作)。
使用curl -v调用lambda的输出:
* TCP_NODELAY set
* Connected to ....execute-api.eu-central-1.amazonaws.com (54.230.197.250) port 443 (#0)
* TLS 1.2 connection using TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256
* Server certificate: *.execute-api.eu-central-1.amazonaws.com
* Server certificate: Symantec Class 3 Secure Server CA - G4
* Server certificate: VeriSign Class 3 Public Primary Certification Authority - G5
> GET /XXX HTTP/1.1
> Host: ....execute-api.eu-central-1.amazonaws.com
> User-Agent: curl/7.51.0
> Accept: */*
>
< HTTP/1.1 200 OK
< Content-Type: application/json
< Content-Length: 65
< Connection: keep-alive
< Date: Wed, 12 Jul 2017 11:55:26 GMT
< x-amzn-RequestId: fe78ee4b-66f8-11e7-a1ac-470fc8454a23
< Access-Control-Allow-Origin: *
< X-Amzn-Trace-Id: sampled=0;root=1-59660e2e-9a6e70cc6d287d90115f73df
< Access-Control-Allow-Credentials: true
< X-Cache: Miss from cloudfront
< Via: 1.1 8ff53834d03bf51be6d4cf56d4e91f1d.cloudfront.net (CloudFront)
< X-Amz-Cf-Id: pgseseaEv_Y12mzVCY07q2EfKOy9SSn_ztmMxvpKmBRPkTDXCjsJ6A==
<
* Curl_http_done: called premature == 0
* Connection #0 to host ....execute-api.eu-central-1.amazonaws.com left intact
我的js文件中的ajax调用如下:
$.ajax({
url: "https://....execute-api.eu-central-1.amazonaws.com/XXX",
contentType: "application/json",
success: function(result) {
document.write(result);
console.log(result);
}});
(请假设curl和ajax调用的网址相同)
现在 - 我从未在网页或控制台上看到结果,但如果我用本地README.md文件替换lambda的URL - 我确实在那里看到了它。另一方面,在curl或浏览器中调用lambda的url会非常好地显示我lambda的输出。
我在这里缺少什么? 谢谢!
答案 0 :(得分:0)
由于此请求来自浏览器,因此存在CORS
个限制。
要使API能够从API自己的域以外的域接收请求,您必须enable CORS for API Gateway Resource
。
另一种选择是使用AWS Javascript SDK
。在这种情况下,您不需要进行此CORS配置。