簡體   English   中英

CORS 政策阻止了獲取“url”的訪問:請求的資源上不存在“Access-Control-Allow-Origin”header。 ReactJS

[英]Access to fetch `url` been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. ReactJS

我正在嘗試使用以下代碼從處於開發模式的 React 應用程序中獲取無服務器 function。

let response = await fetch(url,
       {
           method: 'POST',
           mode: 'cors',
           body: "param=" + paramVar,
        })
        .then(response => response.json());

后端function是一個Python雲function,代碼如下:

def main(request):
    # CORS handling
    if request.method == 'OPTIONS':
        # Allows GET requests from any origin with the Content-Type
        # header and caches preflight response for an 3600s
        headers = {
            'Access-Control-Allow-Origin': '*',
            'Access-Control-Allow-Methods': 'GET, POST',
            'Access-Control-Allow-Headers': 'Content-Type',
            'Access-Control-Max-Age': '3600'
        }

        return ('', 204, headers)
    
    # Set CORS headers for the main request
    headers = {
        'Content-Type':'application/json',
        'Access-Control-Allow-Origin': '*',
        'Access-Control-Allow-Headers': 'Content-Type',
    }

    # Process request
    return (json.dumps(response), 200, headers)

但我不斷收到以下錯誤:

Access to fetch at 'url' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

當我嘗試使用 curl 執行相同的請求時,我得到了正確的響應。 使用 curl 獲取選項給我以下信息:

HTTP/2 204
access-control-allow-headers: Content-Type
access-control-allow-methods: GET, POST
access-control-allow-origin: *
access-control-max-age: 3600
content-type: text/html; charset=utf-8
date: Sun, 16 Aug 2020 01:29:41 GMT

任何人都可以幫助我理解為什么我無法在前端獲得響應? 標頭中存在“Access-Control-Allow-Origin”,所以我真的不明白這個錯誤的原因是什么。

在后端安裝 CORS package。 然后打開您的 server.js 文件或您的任何文件。 然后將其導入文件

const cors = require('cors');

然后使用它

app.use(cors());

重新加載瀏覽器,應該完成!

將內容類型 header 添加到前端的 fetch 方法中,然后重試:

let response = await fetch(url,
       {
           method: 'POST',
           mode: 'cors',
           body: "param=" + paramVar,
           headers: {
             'Content-Type': 'application/json'
       },
  }).then(response => response.json());

實際上,后端存在一個錯誤,該錯誤僅由瀏覽器添加的一些附加標頭觸發。 在這種特殊情況下,服務器返回 404 錯誤,其中不包含我的 header 定義,並會導致 CORS 策略阻止。

在我使用 devtools 跟蹤瀏覽器發送的請求並復制我的 curl 請求中的所有標頭后,我才能夠識別錯誤。 修復 function 邏輯后,問題得到修復。

這是我在 Stack 的第一篇文章

我看到了 OP 的回復,我想我知道他們的意思——因為我自己也遇到了同樣的問題。

基本上,當您向“url”發送請求時,如果 URL 沒有成功回復,那么它會向您發送“錯誤回復”,在我的例子中是“503”。 “503”響應仍然是響應,但此響應不會包含訪問控制允許來源 header,因此瀏覽器(盡職地)回復說它不會接受這個 - 即使它無論如何都是垃圾!

希望這可能對其他人有幫助......干杯

暫無
暫無

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

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