How to enable CORS for simple AJAX web application

天大地大妈咪最大 提交于 2019-12-11 13:54:02

问题


I have searce a lot of solutions about AJAX call CORS, but I still can not get XML data from that other server.

This is console note:

XMLHttpRequest cannot load url.xml. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access

I have follow instructions from: http://www.html5rocks.com/en/tutorials/cors/ section: CORS from jQuery, this is code that I try:

$.ajax({
    type:'GET',
    url:'http://www.someurl.xml',
    contentType:'text/plain',
    xhrFields:{
        withCredentials: false
    },
    headers: {
        'Access-Control-Allow-Origin':'http://localhost:8080',
        'Access-Control-Allow-Method':'GET',
        'Access-Control-Allow-Headers':'Content-Type,x-requested-with,Authorization,Access-Control-Allow-Origin'
    },
    success: function(data){
        var test = data;
    }
});

I know that this question has been asked for many times, but no answer help to fix my problem.

For testing in localhost I am using IIS 8.5


回答1:


The headers section in your $.ajax code adds headers to the request to the server, but CORS headers need to be present on responses from the server.

Working with IIS, you can add those headers with a few lines in the <system.webServer> section of your web.config. Adding this will get you started for GET requests:

<system.webServer>
 <httpProtocol>
  <customHeaders>
   <add name="Access-Control-Allow-Origin" value="*" />
  </customHeaders>
 </httpProtocol>
</system.webServer>

See this post for more information: http://encosia.com/using-cors-to-access-asp-net-services-across-domains/




回答2:


The CORS headers must be sent by the server you are making the call to, you cannot provide them with the request itself.

When making a request across domains, your browser will perform a preflight request to get the relevant CORS headers before actually requesting data (I believe this uses the OPTION method).

If the CORS headers from preflight include the current origin or a wildcard matching it, then the browser will continue on with the real request and fetch some data.



来源:https://stackoverflow.com/questions/29748338/how-to-enable-cors-for-simple-ajax-web-application

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!