fetch get request mode to no-cors

Posted in :

在 extension 的 background 裡存取外部URL時, 發生錯誤訊息:

Access to fetch at 'http://127.0.0.1:16888/ocr' from origin 'chrome-extension://xxx' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: 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.

執行畫面:

說明:

  • 第1次呼叫,伺服器還沒開,顯示錯誤: Failed to fetch
  • 第2次呼叫,伺服器還沒開,顯示錯誤: has been blocked by CORS policy

解法:

fetch(data_url,{
    mode: 'no-cors',
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      key1: 'value1',
      key2: 'value2'
    })
})
.then(response =>
{
})

加入 mode: ‘no-cors’

這時候, 傳回結果會是0

因為 cors 才能存取內容:

When using fetch with mode: ‘no-cors’, an opaque response is received. To access the response, mode: ‘cors’ must be used, and the server must send the required CORS headers.

絕對不能從 client 端突破 cors 的限制,mode: ‘no-cors’ 不是說加了就可以突破 cors 的限制。

To prevent receiving an opaque response without JSON, it is necessary to use CORS.

Why is my no-cors fetch() not ok even if the request succeed?, when you have mode:’no-cors’. you will get a response with type: “opaque”. which returns status:0. and since ok is only true on status in

結論,改用 JQuery 的 ajax 一樣被擋掉, 只能透過其他方式來解, 如果你是在寫 browser extension, 把存取的 fecth 放在 background.js 之中, 並設定host_permissions 就可以正常了.

"host_permissions": [
    "http://your-url-here/*"
  ]

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *