爲什麼我的 JavaScript 代碼會收到“請求的資源上不存在‘Access-Control-Allow-Origin’標頭”錯誤,而 Postman 則沒有?

問題:

Mod note : This question is about why XMLHttpRequest / fetch /etc. Mod注:這個問題是關於爲什麼XMLHttpRequest / fetch /etc。 on the browser are subject to the Same Access Policy restrictions (you get errors mentioning CORB or CORS) while Postman is not.在瀏覽器上受相同訪問策略限制(您會收到提及 CORB 或 CORS 的錯誤),而 Postman 則不受此限制。 This question is not about how to fix a "No 'Access-Control-Allow-Origin'..." error.這個問題不是關於如何解決“沒有‘訪問控制-允許-來源’...”錯誤。 It's about why they happen.這是關於它們發生的原因。

Please stop posting :請停止發帖

  • CORS configurations for every language/framework under the sun.陽光下每種語言/框架的 CORS 配置。 Instead find your relevant language/framework's question .而是找到您相關的語言/框架問題
  • 3rd party services that allow a request to circumvent CORS允許請求繞過 CORS 的第 3 方服務
  • Command line options for turning off CORS for various browsers用於關閉各種瀏覽器的 CORS 的命令行選項

I am trying to do authorization using JavaScript by connecting to the RESTful API built-in Flask .我試圖通過連接到RESTful API內置Flask來使用JavaScript進行授權。 However, when I make the request, I get the following error:但是,當我提出請求時,出現以下錯誤:

XMLHttpRequest cannot load http://myApiUrl/login. XMLHttpRequest 無法加載 http://myApiUrl/login。 No 'Access-Control-Allow-Origin' header is present on the requested resource.請求的資源上不存在“Access-Control-Allow-Origin”標頭。 Origin 'null' is therefore not allowed access.因此,不允許訪問 Origin 'null'。

I know that the API or remote resource must set the header, but why did it work when I made the request via the Chrome extension Postman ?我知道 API 或遠程資源必須設置標頭,但是爲什麼當我通過 Chrome 擴展Postman發出請求時它起作用了?

This is the request code:這是請求代碼:

$.ajax({
    type: "POST",
    dataType: 'text',
    url: api,
    username: 'user',
    password: 'pass',
    crossDomain : true,
    xhrFields: {
        withCredentials: true
    }
})
    .done(function( data ) {
        console.log("done");
    })
    .fail( function(xhr, textStatus, errorThrown) {
        alert(xhr.responseText);
        alert(textStatus);
    });

解決方案:

參考一: https://en.stackoom.com/question/1M42n參考二: https://stackoom.com/question/1M42n
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章