簡體   English   中英

CORS 策略已阻止訪問“來自原點”的獲取:請求的資源上不存在“Access-Control-Allow-Origin”header

[英]Access to fetch at '' from origin '' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource

I have this api (method get) that is connected to a lambda function that does a simple select from a database, if i test the endpoint with postman with a null body it does work (if i understood, postman is not under the same CORS政策),以及在瀏覽器上輸入端點。 郵差

瀏覽器

但是,當我嘗試從一個簡單的 js 中獲取數據時,我收到錯誤消息:從來源 'http://localhost' 訪問 '...' 的數據已被 CORS 策略阻止:無 'Access-Control-Allow -Origin' header 出現在請求的資源上。 如果不透明的響應滿足您的需求,請將請求的模式設置為“no-cors”以獲取禁用 CORS 的資源。

在此處輸入圖像描述

我在 API 網關中啟用了 CORS,兩者都帶有 Enable CORS 選項在此處輸入圖像描述 並在創建新資源時啟用 API 網關 CORS 在此處輸入圖像描述

如果我使用網關測試我的端點,我還會得到 Allow-content-allow-origin: * 在我的響應中 header: 在此處輸入圖像描述

我應該怎么做才能解決這個問題?

這是 JS 獲取:

    console.log("pre fetch");

Show();
console.log("post fetch");
function Show(){
fetch("...").then(onResponse);//.then(onJson);
}
function onResponse(response){
    console.log(response);
    return response.json();
}

我刪除了 onJson 以避免混淆,但即使在同樣的問題中也是如此。

嘗試將其包含在您的 function 中,就像這樣,我希望這會起作用:

const headers = {'Content-Type':'application/json',
                    'Access-Control-Allow-Origin':'*',
                    'Access-Control-Allow-Methods':'POST,PATCH,OPTIONS'}
const response = {
    statusCode: 200,
    headers:headers,
    body: JSON.stringify(X),
};
return response;

這里X是您要返回的響應。

制作了有關如何修復它的視頻: https://youtu.be/nJXkFgG5TbQ

您需要將 go 插入 Lambda function 並添加特殊代碼:

原始(不起作用):

exports.handler = async (event) => {
    // TODO implement
    const response = {
        statusCode: 200,
        body: JSON.stringify('Hello from Lambda!'),
    };
    return response;
};

新的,有效的:

exports.handler = async (event) => {
    // TODO implement
    const response = {
        statusCode: 200,
                headers: {
            "Access-Control-Allow-Headers" : "Content-Type",
            "Access-Control-Allow-Origin": "*",
            "Access-Control-Allow-Methods": "OPTIONS,POST,GET"
        },
        body: JSON.stringify('Hello from Lambda!'),
    };
    return response;
};

您可以在此處找到此解決方案: https://docs.aws.amazon.com/apigateway/latest/developerguide/how-to-cors.html

只有你需要更換:

  "Access-Control-Allow-Origin": "https://www.example.com",

            "Access-Control-Allow-Origin": "*",

特別感謝用戶 KnowledgeGainer

ALSO, you need to enable CORS on Gateway API side, just follow instruction from here: https://docs.aws.amazon.com/apigateway/latest/developerguide/how-to-cors-console.html

如果您使用的是 Node.js,則需要安裝 cors。 npm 安裝 cors。 安裝 cors 后,將其包含在您正在使用 fetch function 的頁面中,如下所示; 常量 cors = 要求('cors'); app.use(cors()); 錯誤將得到解決。

感謝 reddit 用戶 u/LipSoft,通過在 API 部分的 Enable CORS 的標題中添加“Origin”來解決。 屏幕

現在問題消失了。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM