簡體   English   中英

使用前端 Javascript 獲取 API 返回 CORS 和 302 錯誤

[英]Fetch API with frontend Javascript returns CORS and 302 error

我正在嘗試獲取過去對我有用但現在正在返回的 API:

[Error] Preflight response is not successful. Status code: 302
[Error] Fetch API cannot load http://api-im-trying-to-fetch due to access control checks.
[Error] Failed to load resource: Preflight response is not successful. Status code: 302 (states, line 0)

我嘗試禁用跨域限制並向標頭添加信息,例如 mode:'no-corse',但沒有任何效果。 我想知道這是否與 API 有關,我對此無能為力。 謝謝!

const apiKey = 'secret-api';
const endpoint = 'url of api';

export const getAbortionInfo = async() => {
    try{
        const response = await fetch(endpoint, {
            headers: {
                'token': apiKey
            }
        });
            if(response.ok){
                const jsonResponse = await response.json();
                console.log(jsonResponse)
            }
            throw new Error('Resquest failed!')
    }
    catch(error){
        console.log(error)
    }
}

當瀏覽器需要來自服務器的許可(通過 CORS)來發出真正的請求時,會發送一個預檢請求。

您需要獲得您要請求的 URL 的許可。

CORS 規范不允許您重定向到其他地方。

您需要發出一個不會導致服務器響應重定向的請求。 這可以簡單到將您從https://example.com/api/foo請求的 URL 更改為https://example.com/api/foo/ 使用瀏覽器開發人員工具的網絡選項卡應該會顯示重定向響應,並讓您檢查Location響應 header 以找出請求被重定向到的位置。


請注意,一旦您解決了重定向問題,您仍然需要服務器發送 CORS 響應標頭以提供訪問權限。

使用mode: 'no-cors'無濟於事。 這告訴瀏覽器您不想做任何需要 CORS 權限的事情,如果遇到 CORS 問題,它應該靜默失敗。 設置非標准的 HTTP 標頭(例如token )需要 CORS 權限。

您需要更新服務器上的 CORS 標頭。 具體來說,你需要設置你的allow-access-control-origin header,允許哪些HTTP方法,允許傳輸什么類型的數據。 它應該看起來與此非常相似(同樣,在服務器端:!):

  response.appendHeader("Access-Control-Allow-Origin", "*");
  response.appendHeader("Access-Control-Allow-Methods", "OPTIONS, POST, GET");
  response.appendHeader("Content-Type", "application/json");

暫無
暫無

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

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