繁体   English   中英

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

[英]S3 Lambda API Error - not allowed by Access-Control-Allow-Origin

我有一个Lambda函数,可以从脚本返回文本,我设置了一个API以使用GET Request获取数据,并将其部署进行测试。

当我单击测试API时,我会成功获得结果。

我的index.html中有此代码

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();

            }

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

<?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>

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

[Error] Origin https://s3.amazonaws.com is not allowed by Access-Control-Allow-Origin.
[Error] Failed to load resource: Origin https://s3.amazonaws.com is not allowed by Access-Control-Allow-Origin. (myServerlessWebpage, line 0)
[Error] XMLHttpRequest cannot load [myapiwebsite] due to access control checks.

我遇到了同样的问题,发现可以通过服务器代理请求来“修复”此问题。

所以,在前面我提出请求, 表示服务器,然后在服务器端也求AWS API。
例如,带有用于请求的节点获取模块:

//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请求。

另外,您会发现本文非常有帮助,并且可能会为您的问题找到另一种解决方案。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM