2017-06-02 76 views
1

我正在對不同的域進行ajax調用。我的團隊成員將Access-Control-Allow-Origin標頭添加到http://localhost:3000在後端添加Access-Control-Allow-Origin頭後,爲什麼會出現cors問題?

$.ajax({ 
      type: 'GET', 
      url: myurl, 
      beforeSend: function(xhr) { 
       xhr.setRequestHeader('Authorization', 'Bearer '+authorization); 
      }, 
      crossDomain: true, 
      // xhrFields: { 
      // withCredentials: true 
      // }, 
      contentType: 'application/json', 
      dataType: 'JSON', 
      success: function (response) { 
      if(time_one === 0){ 
       main_result = response; 
       time_one++; 
      } 
      if(response.length==0){ 
       alert("NO Data; Try a valid search") 
       $('.row3, #paging').hide(); 
       $('.loading-gif').show(); 
       $('#table').html(''); 
       myCallBack(main_result); 
      } 
      else{ 
       $('#table').html('') 
       myCallBack(response); 
      } 
      }, 
      error: function(err) { 
      $('.loading-gif').hide(); 
      $(".pageblocker").hide(); 
      alert('Error: '+JSON.stringify(err)); 
      myCallBack(main_result) 
      } 
     }); 

如果我嘗試這種方式,我越來越'Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access.'我不明白爲什麼我即使添加了ACAO頭之後得到這樣的錯誤類型。

而且我還注意到另一個錯誤,如果我添加'withCredentials'屬性。 ' 'Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. Origin 'http://localhost:3000' is therefore not allowed access. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.'我不明白這兩個錯誤之間的區別。

回答

1

服務器myurl必須返回Access-Control-Allow-Origin響應標頭。

如果您無權訪問myurl服務器的服務器環境以將該服務器配置爲發送Access-Control-Allow-Origin響應標頭,那麼您需要通過代理進行請求。您可以在"No 'Access-Control-Allow-Origin' header is present on the requested resource"的答案中找到有關設置該類代理的更多詳細信息。

反正事實添加Access-Control-Allow-Originhttp://localhost:3000後端具有在這種情況下沒有效果,預計-因爲Access-Control-Allow-Origin響應頭必須由一個請求到由服務器發送。 http://localhost:3000不是這樣 - 它是服務於啓動請求的前端JavaScript代碼的服務器。

https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS是瞭解所有這些東西如何工作的最佳資源。這裏其他一些答案看一看:

+0

嗯,有點混亂,但我會通過它獲得。當我添加'withCredentials'屬性時,其他錯誤的含義是什麼?它說mdn dev ntk暴露頭。我在考慮公開標題頭部標題對所有人都是可見的,包括身份驗證令牌。 –

+0

「公開標題」意味着瀏覽器*是否會將響應標頭展示給您的前端JavaScript代碼。服務器無論何時都會在響應中發送一整套標題,並且瀏覽器會得到完整的響應,包括服務器發送的所有標題。但瀏覽器不會向您的前端JavaScript代碼公開某些標頭,除非服務器在響應中包含了Access-Control-Expose-Headers響應標頭,該標頭包含您的前端JavaScript代碼想要訪問的特定標頭名稱 – sideshowbarker

+0

謝謝響應!說實話,這是我的頭。你能否建議我在哪裏查看這個基礎知識,以便我能理解你的答案? –

相關問題