No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin '…' is therefore not allowed access

后端 未结 11 1737
醉话见心
醉话见心 2020-11-22 14:27

I\'m using .htaccess to rewrite urls and I used html base tag in order to make it work.

Now, when I try to make an ajax request I get the following error:

相关标签:
11条回答
  • 2020-11-22 14:35

    you have to put the headers keys/values in options method response. for example if you have resource at http://mydomain.com/myresource then, in your server code you write

    //response handler
    void handleRequest(Request request, Response response) {
        if(request.method == "OPTIONS") {
           response.setHeader("Access-Control-Allow-Origin","http://clientDomain.com")
           response.setHeader("Access-Control-Allow-Methods", "GET,POST,PUT,DELETE,OPTIONS");
           response.setHeader("Access-Control-Allow-Headers", "Content-Type");
        }
    
    
    
    }
    
    0 讨论(0)
  • 2020-11-22 14:39

    Use addHeader Instead of using setHeader method,

    response.addHeader("Access-Control-Allow-Origin", "*");
    

    * in above line will allow access to all domains.


    For allowing access to specific domain only:

    response.addHeader("Access-Control-Allow-Origin", "http://www.example.com");
    

    Check this blog post.

    0 讨论(0)
  • 2020-11-22 14:40

    Pleaes find the Function used in XMLHTTPREQUEST in Javascript for setting up the request headers.

    ...
    
    xmlHttp.setRequestHeader("Access-Control-Allow-Origin", "http://www.example.com");
    ...
    </script>
    
    

    Reference: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/setRequestHeader

    0 讨论(0)
  • 2020-11-22 14:44

    Add this to you PHP file or main controller

    header("Access-Control-Allow-Origin: http://localhost:9000");
    
    0 讨论(0)
  • 2020-11-22 14:50

    For .NET server can configure this in web.config as shown below

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

    For instance lets say, if the server domain is http://live.makemypublication.com and client is http://www.makemypublication.com then configure in server's web.config as below

     <system.webServer>
       <httpProtocol>
         <customHeaders>
           <add name="Access-Control-Allow-Origin" value="http://www.makemypublication.com" />
         </customHeaders>
      </httpProtocol>
     </system.webServer>
    
    0 讨论(0)
提交回复
热议问题