S3 Lambda API错误 - Access-Control-Allow-Origin不允许

时间:2018-04-14 22:51:11

标签: amazon-web-services amazon-s3 aws-lambda

我有一个从脚本返回文本的Lambda函数,我设置了一个API来使用Path获取数据并将其部署用于测试。

当我点击测试API时,我成功地获得了结果。

我在index.html中有这段代码

GET Request

在我的S3上,该文件是公共的,我的CORS是

function myFunction() {
                var xhttp = new XMLHttpRequest();
                xhttp.onreadystatechange = function(e) {
                    console.log(e)
                    if (this.readyState == 4 && this.status == 200) {
                    document.getElementById("my-demo").innerHTML = this.responseText;
                    }
                };
                xhttp.open("GET", "[link to get API]", true);
                xhttp.send();

            }

网页加载,但我不断收到这些错误

<?xml version="1.0" encoding="UTF-8"?>
<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<CORSRule>
    <AllowedOrigin>*</AllowedOrigin>
    <AllowedOrigin>http://*</AllowedOrigin>
    <AllowedOrigin>https://*</AllowedOrigin>
    <AllowedMethod>GET</AllowedMethod>
    <MaxAgeSeconds>3000</MaxAgeSeconds>
    <AllowedHeader>*</AllowedHeader>
</CORSRule>
</CORSConfiguration>

1 个答案:

答案 0 :(得分:0)

我遇到了同样的问题,发现我可以修复&#34;通过我的服务器代理我的请求的这种行为。

因此,我在前面向express服务器发出请求,然后在服务器端向AWS API发出请求。
例如,node-fetch模块用于请求:

//front
var xhttp = new XMLHttpRequest();
            xhttp.onreadystatechange = function(e) {
                console.log(e)
                if (this.readyState == 4 && this.status == 200) {
                document.getElementById("my-demo").innerHTML = this.responseText;
                }
            };
            xhttp.open("GET", "[link to get your server]", true);
            xhttp.send();


// backend 
var fetch = require('node-fetch'):
// your server code here....

app.get('/[link to get your server]', async (request, response) => {
  // parse data from request and 
  var apiRequest = await fetch([link to get API]);
  var result = await fetch.json();
  // send result from AWS api to front.
  res.send(result);
})

因此,解决方案是通过您的服务器代理您的AWS API请求。

另外,您可以找到这个article非常有用,也许可以找到解决问题的另一种解决方案。