2017-06-02 72 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

谢谢响应!说实话,这是我的头。你能否建议我在哪里查看这个基础知识,以便我能理解你的答案? –

相关问题