[英]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.