How does Access-Control-Allow-Origin header work?












892















Apparently, I have completely misunderstood its semantics. I thought of something like this:




  1. A client downloads javascript code MyCode.js from http://siteA - the origin.

  2. The response header of MyCode.js contains Access-Control-Allow-Origin: http://siteB, which I thought meant that MyCode.js was allowed to make cross-origin references to the site B.

  3. The client triggers some functionality of MyCode.js, which in turn make requests to http://siteB, which should be fine, despite being cross-origin requests.


Well, I am wrong. It does not work like this at all. So, I have read Cross-origin resource sharing and attempted to read Cross-Origin Resource Sharing in w3c recommendation



One thing is sure - I still do not understand how am I supposed to use this header.



I have full control of both site A and site B. How do I enable the javascript code downloaded from the site A to access resources on the site B using this header?



P.S.



I do not want to utilize JSONP.










share|improve this question




















  • 2





    I'm not sure, but I believe that setting the header this way allows code on site B to fetch http://siteA/MyCode.js.

    – pimvdb
    May 17 '12 at 13:26








  • 4





    But how??? In order to get the header value one has to fetch the resource first, but the resource is cross-origin and so shouldn't the browser block the request in the first place?

    – mark
    May 17 '12 at 13:33











  • What you described actually resembles another practice, Content Security Policy

    – Alex
    Jun 9 '16 at 17:03






  • 2





    @mark You don't have to fetch the resource in order to get the headers. The HTTP HEADER method will return headers-only. And in the case of CORS, a preflight check is done using the HTTP OPTIONS method which doesn't return the body either. apsillers answer describes this nicely stackoverflow.com/posts/10636765/revisions.

    – Matt
    Sep 9 '16 at 23:50
















892















Apparently, I have completely misunderstood its semantics. I thought of something like this:




  1. A client downloads javascript code MyCode.js from http://siteA - the origin.

  2. The response header of MyCode.js contains Access-Control-Allow-Origin: http://siteB, which I thought meant that MyCode.js was allowed to make cross-origin references to the site B.

  3. The client triggers some functionality of MyCode.js, which in turn make requests to http://siteB, which should be fine, despite being cross-origin requests.


Well, I am wrong. It does not work like this at all. So, I have read Cross-origin resource sharing and attempted to read Cross-Origin Resource Sharing in w3c recommendation



One thing is sure - I still do not understand how am I supposed to use this header.



I have full control of both site A and site B. How do I enable the javascript code downloaded from the site A to access resources on the site B using this header?



P.S.



I do not want to utilize JSONP.










share|improve this question




















  • 2





    I'm not sure, but I believe that setting the header this way allows code on site B to fetch http://siteA/MyCode.js.

    – pimvdb
    May 17 '12 at 13:26








  • 4





    But how??? In order to get the header value one has to fetch the resource first, but the resource is cross-origin and so shouldn't the browser block the request in the first place?

    – mark
    May 17 '12 at 13:33











  • What you described actually resembles another practice, Content Security Policy

    – Alex
    Jun 9 '16 at 17:03






  • 2





    @mark You don't have to fetch the resource in order to get the headers. The HTTP HEADER method will return headers-only. And in the case of CORS, a preflight check is done using the HTTP OPTIONS method which doesn't return the body either. apsillers answer describes this nicely stackoverflow.com/posts/10636765/revisions.

    – Matt
    Sep 9 '16 at 23:50














892












892








892


421






Apparently, I have completely misunderstood its semantics. I thought of something like this:




  1. A client downloads javascript code MyCode.js from http://siteA - the origin.

  2. The response header of MyCode.js contains Access-Control-Allow-Origin: http://siteB, which I thought meant that MyCode.js was allowed to make cross-origin references to the site B.

  3. The client triggers some functionality of MyCode.js, which in turn make requests to http://siteB, which should be fine, despite being cross-origin requests.


Well, I am wrong. It does not work like this at all. So, I have read Cross-origin resource sharing and attempted to read Cross-Origin Resource Sharing in w3c recommendation



One thing is sure - I still do not understand how am I supposed to use this header.



I have full control of both site A and site B. How do I enable the javascript code downloaded from the site A to access resources on the site B using this header?



P.S.



I do not want to utilize JSONP.










share|improve this question
















Apparently, I have completely misunderstood its semantics. I thought of something like this:




  1. A client downloads javascript code MyCode.js from http://siteA - the origin.

  2. The response header of MyCode.js contains Access-Control-Allow-Origin: http://siteB, which I thought meant that MyCode.js was allowed to make cross-origin references to the site B.

  3. The client triggers some functionality of MyCode.js, which in turn make requests to http://siteB, which should be fine, despite being cross-origin requests.


Well, I am wrong. It does not work like this at all. So, I have read Cross-origin resource sharing and attempted to read Cross-Origin Resource Sharing in w3c recommendation



One thing is sure - I still do not understand how am I supposed to use this header.



I have full control of both site A and site B. How do I enable the javascript code downloaded from the site A to access resources on the site B using this header?



P.S.



I do not want to utilize JSONP.







javascript cross-domain cors






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Jul 28 '16 at 9:00









Sujania

3,07563157




3,07563157










asked May 17 '12 at 13:23









markmark

19.8k56186377




19.8k56186377








  • 2





    I'm not sure, but I believe that setting the header this way allows code on site B to fetch http://siteA/MyCode.js.

    – pimvdb
    May 17 '12 at 13:26








  • 4





    But how??? In order to get the header value one has to fetch the resource first, but the resource is cross-origin and so shouldn't the browser block the request in the first place?

    – mark
    May 17 '12 at 13:33











  • What you described actually resembles another practice, Content Security Policy

    – Alex
    Jun 9 '16 at 17:03






  • 2





    @mark You don't have to fetch the resource in order to get the headers. The HTTP HEADER method will return headers-only. And in the case of CORS, a preflight check is done using the HTTP OPTIONS method which doesn't return the body either. apsillers answer describes this nicely stackoverflow.com/posts/10636765/revisions.

    – Matt
    Sep 9 '16 at 23:50














  • 2





    I'm not sure, but I believe that setting the header this way allows code on site B to fetch http://siteA/MyCode.js.

    – pimvdb
    May 17 '12 at 13:26








  • 4





    But how??? In order to get the header value one has to fetch the resource first, but the resource is cross-origin and so shouldn't the browser block the request in the first place?

    – mark
    May 17 '12 at 13:33











  • What you described actually resembles another practice, Content Security Policy

    – Alex
    Jun 9 '16 at 17:03






  • 2





    @mark You don't have to fetch the resource in order to get the headers. The HTTP HEADER method will return headers-only. And in the case of CORS, a preflight check is done using the HTTP OPTIONS method which doesn't return the body either. apsillers answer describes this nicely stackoverflow.com/posts/10636765/revisions.

    – Matt
    Sep 9 '16 at 23:50








2




2





I'm not sure, but I believe that setting the header this way allows code on site B to fetch http://siteA/MyCode.js.

– pimvdb
May 17 '12 at 13:26







I'm not sure, but I believe that setting the header this way allows code on site B to fetch http://siteA/MyCode.js.

– pimvdb
May 17 '12 at 13:26






4




4





But how??? In order to get the header value one has to fetch the resource first, but the resource is cross-origin and so shouldn't the browser block the request in the first place?

– mark
May 17 '12 at 13:33





But how??? In order to get the header value one has to fetch the resource first, but the resource is cross-origin and so shouldn't the browser block the request in the first place?

– mark
May 17 '12 at 13:33













What you described actually resembles another practice, Content Security Policy

– Alex
Jun 9 '16 at 17:03





What you described actually resembles another practice, Content Security Policy

– Alex
Jun 9 '16 at 17:03




2




2





@mark You don't have to fetch the resource in order to get the headers. The HTTP HEADER method will return headers-only. And in the case of CORS, a preflight check is done using the HTTP OPTIONS method which doesn't return the body either. apsillers answer describes this nicely stackoverflow.com/posts/10636765/revisions.

– Matt
Sep 9 '16 at 23:50





@mark You don't have to fetch the resource in order to get the headers. The HTTP HEADER method will return headers-only. And in the case of CORS, a preflight check is done using the HTTP OPTIONS method which doesn't return the body either. apsillers answer describes this nicely stackoverflow.com/posts/10636765/revisions.

– Matt
Sep 9 '16 at 23:50












13 Answers
13






active

oldest

votes


















1141














Access-Control-Allow-Origin is a CORS (Cross-Origin Resource Sharing) header.



When Site A tries to fetch content from Site B, Site B can send an Access-Control-Allow-Origin response header to tell the browser that the content of this page is accessible to certain origins. (An origin is a domain, plus a scheme and port number.) By default, Site B's pages are not accessible to any other origin; using the Access-Control-Allow-Origin header opens a door for cross-origin access by specific requesting origins.



For each resource/page that Site B wants to make accessible to Site A, Site B should serve its pages with the response header:



Access-Control-Allow-Origin: http://siteA.com


Modern browsers will not block cross-domain requests outright. If Site A requests a page from Site B, the browser will actually fetch the requested page on the network level and check if the response headers list Site A as a permitted requester domain. If Site B has not indicated that Site A is allowed to access this page, the browser will trigger the XMLHttpRequest's error event and deny the response data to the requesting JavaScript code.



Non-simple requests



What happens on the network level can be slightly more complex than explained above. If the request is a "non-simple" request, the browser first sends a data-less "preflight" OPTIONS request, to verify that the server will accept the request. A request is non-simple when either (or both):




  • using an HTTP verb other than GET or POST (e.g. PUT, DELETE)

  • using non-simple request headers; the only simple requests headers are:


    • Accept

    • Accept-Language

    • Content-Language


    • Content-Type (this is only simple when its value is application/x-www-form-urlencoded, multipart/form-data, or text/plain)




If the server responds to the OPTIONS preflight with appropriate response headers (Access-Control-Allow-Headers for non-simple headers, Access-Control-Allow-Methods for non-simple verbs) that match the non-simple verb and/or non-simple headers, then the browser sends the actual request.



Supposing that Site A wants to send a PUT request for /somePage, with a non-simple Content-Type value of application/json, the browser would first send a preflight request:



OPTIONS /somePage HTTP/1.1
Origin: http://siteA.com
Access-Control-Request-Method: PUT
Access-Control-Request-Headers: Content-Type


Note that Access-Control-Request-Method and Access-Control-Request-Headers are added by the browser automatically; you do not need to add them. This OPTIONS preflight gets the successful response headers:



Access-Control-Allow-Origin: http://siteA.com
Access-Control-Allow-Methods: GET, POST, PUT
Access-Control-Allow-Headers: Content-Type


When sending the actual request (after preflight is done), the behavior is identical to how a simple request is handled. In other words, a non-simple request whose preflight is successful is treated the same as a simple request (i.e., the server must still send Access-Control-Allow-Origin again for the actual response).



The browsers sends the actual request:



PUT /somePage HTTP/1.1
Origin: http://siteA.com
Content-Type: application/json

{ "myRequestContent": "JSON is so great" }


And the server sends back an Access-Control-Allow-Origin, just as it would for a simple request:



Access-Control-Allow-Origin: http://siteA.com


See Understanding XMLHttpRequest over CORS for a little more information about non-simple requests.






share|improve this answer





















  • 4





    But MyCode.js cannot reach for site B in the first place! How will this header arrive at the client? BTW, kudos for the light life glider in the avatar.

    – mark
    May 17 '12 at 13:36








  • 5





    I edited with clarification: the browser actually does perform a network fetch on site B to check the Access-Control-Allow-Origin header, but it might not provide the response to the JS code on site A if the header doesn't allow site A to have it. (P.S. Thanks :) )

    – apsillers
    May 17 '12 at 13:41








  • 2





    Indeed, I do not see any record of the download in Fiddler, unless the cross-origin request is approved. Interesting...

    – mark
    May 17 '12 at 14:18






  • 14





    @Jwan622 A fundamental "why?" question like that is probably out of scope for this particular answer, which is just about rules & mechanics. Basically, the browser allows you, the human sitting at the computer, see any resource from any origin. It disallows scripts (which could be written by anyone) from reading resources from origins that are different from the origin of the page running the script. Some related questions are programmers.stackexchange.com/q/216605 and What is the threat model for the same origin policy?

    – apsillers
    Jul 12 '15 at 17:55






  • 2





    In case of using an authentication, Access-Control-Allow-Origin does not accept the * in some browsers (FF and Chrome AFAIK). So in this case you have to specify the value from the Origin header. Hope that this will help someone.

    – Zsolti
    Sep 9 '16 at 19:59



















107














Cross-Origin Request Sharing - CORS (A.K.A. Cross-Domain AJAX request) is an issue that most web developers might encounter, according to Same-Origin-Policy, browsers restrict client JavaScript in a security sandbox, usually JS cannot directly communicate with a remote server from a different domain. In the past developers created many tricky ways to achieve Cross-Domain resource request, most commonly using ways are:




  1. Use Flash/Silverlight or server side as a "proxy" to communicate
    with remote.

  2. JSON With Padding (JSONP).

  3. Embeds remote server in an iframe and communicate through fragment or window.name, refer here.


Those tricky ways have more or less some issues, for example JSONP might result in security hole if developers simply "eval" it, and #3 above, although it works, both domains should build strict contract between each other, it neither flexible nor elegant IMHO:)



W3C had introduced Cross-Origin Resource Sharing (CORS) as a standard solution to provide a safe, flexible and a recommended standard way to solve this issue.



The Mechanism



From a high level we can simply deem CORS is a contract between client AJAX call from domain A and a page hosted on domain B, a typical Cross-Origin request/response would be:



DomainA AJAX request headers



Host DomainB.com
User-Agent Mozilla/5.0 (Windows NT 6.1; WOW64; rv:2.0) Gecko/20100101 Firefox/4.0
Accept text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8,application/json
Accept-Language en-us;
Accept-Encoding gzip, deflate
Keep-Alive 115
Origin http://DomainA.com


DomainB response headers



Cache-Control private
Content-Type application/json; charset=utf-8
Access-Control-Allow-Origin DomainA.com
Content-Length 87
Proxy-Connection Keep-Alive
Connection Keep-Alive


The blue parts I marked above were the kernal facts, "Origin" request header "indicates where the cross-origin request or preflight request originates from", the "Access-Control-Allow-Origin" response header indicates this page allows remote request from DomainA (if the value is * indicate allows remote requests from any domain).



As I mentioned above, W3 recommended browser to implement a "preflight request" before submiting the actually Cross-Origin HTTP request, in a nutshell it is an HTTP OPTIONS request:



OPTIONS DomainB.com/foo.aspx HTTP/1.1


If foo.aspx supports OPTIONS HTTP verb, it might return response like below:



HTTP/1.1 200 OK
Date: Wed, 01 Mar 2011 15:38:19 GMT
Access-Control-Allow-Origin: http://DomainA.com
Access-Control-Allow-Methods: POST, GET, OPTIONS, HEAD
Access-Control-Allow-Headers: X-Requested-With
Access-Control-Max-Age: 1728000
Connection: Keep-Alive
Content-Type: application/json


Only if the response contains "Access-Control-Allow-Origin" AND its value is "*" or contain the domain who submitted the CORS request, by satisfying this mandtory condition browser will submit the actual Cross-Domain request, and cache the result in "Preflight-Result-Cache".



I blogged about CORS three years ago: AJAX Cross-Origin HTTP request






share|improve this answer


























  • This answer made me realize why i was suddenly getting an issue without using this header for POST and GET requests. I had accidently opened the index.html file directly from disk, so the URL the client was accessing on node.js was thought to be cross-domain, while it was simply running on localhost. Accessing via the URL (as one would usually do) "solved" my issue...

    – LuqJensen
    Jan 8 '17 at 21:06











  • Would a domain in an external network able to communite with a domain on an internal network?

    – Si8
    Mar 31 '17 at 1:47



















42














Question is a bit too old to answer, but I am posting this for any future reference to this question.



According to this Mozilla Developer Network article,




A resource makes a cross-origin HTTP request when it requests a resource from a different domain, or port than the one which the first resource itself serves.




enter image description here



An HTML page served from http://domain-a.com makes an <img> src request for http://domain-b.com/image.jpg.

Many pages on the web today load resources like CSS stylesheets, images and scripts from separate domains (thus it should be cool).



Same-Origin Policy



For security reasons, browsers restrict cross-origin HTTP requests initiated from within scripts.

For example, XMLHttpRequest and Fetch follow the same-origin policy.

So, a web application using XMLHttpRequest or Fetch could only make HTTP requests to its own domain.



Cross-Origin Resource Sharing (CORS)



To improve web applications, developers asked browser vendors to allow cross-domain requests.



The Cross-Origin Resource Sharing (CORS) mechanism gives web servers cross-domain access controls, which enable secure cross-domain data transfers.

Modern browsers use CORS in an API container - such as XMLHttpRequest or Fetch - to mitigate risks of cross-origin HTTP requests.



How CORS works (Access-Control-Allow-Origin header)



Wikipedia:




The CORS standard describes new HTTP headers which provide browsers and servers a way to request remote URLs only when they have permission.



Although some validation and authorization can be performed by the server, it is generally the browser's responsibility to support these headers and honor the restrictions they impose.




Example





  1. The browser sends the OPTIONS request with an Origin HTTP header.



    The value of this header is the domain that served the parent page. When a page from http://www.example.com attempts to access a user's data in service.example.com, the following request header would be sent to service.example.com:



    Origin: http://www.example.com




  2. The server at service.example.com may respond with:





    • An Access-Control-Allow-Origin (ACAO) header in its response indicating which origin sites are allowed.

      For example:



      Access-Control-Allow-Origin: http://www.example.com



    • An error page if the server does not allow the cross-origin request



    • An Access-Control-Allow-Origin (ACAO) header with a wildcard that allows all domains:



      Access-Control-Allow-Origin: *










share|improve this answer
























  • How to set none are allowed to acees some thing like Access-Control-Allow-Origin:null

    – Subin C Poonamgode
    Aug 25 '17 at 6:18













  • When I don't want to allow anyone to access my resources through CORS, what value should I set for Access-Control-Allow-Origin ? I mean the negation of Access-Control-Allow-Origin: *

    – Subin C Poonamgode
    Aug 31 '17 at 13:54











  • Just dont set anything, for that purpose

    – Trix
    Aug 31 '17 at 13:56



















8














If you want just to test a cross domain application in which the browser blocks your request, then you can just open your browser in unsafe mode and test your application without changing your code and without making your code unsafe.
From MAC OS you can do this from the terminal line:



open -a Google Chrome --args --disable-web-security --user-data-dir





share|improve this answer































    7














    Using React and Axios, join proxy link to the URL and add header as shown below



    https://cors-anywhere.herokuapp.com/ + Your API URL



    Just by adding the Proxy link will work, but it can also throw error for No Access again. Hence better to add header as shown below.



    axios.get(`https://cors-anywhere.herokuapp.com/[YOUR_API_URL]`,{headers: {'Access-Control-Allow-Origin': '*'}})
    .then(response => console.log(response:data);
    }





    share|improve this answer



















    • 2





      Please don't do this. Using a proxy link is like handing over user cookies to a middle-man. Should be illegal IMHO

      – captainserious
      Dec 9 '17 at 10:12











    • Thanks for sharing this! You saved my day. You think I can use this hack on production?

      – blvckasvp
      Oct 19 '18 at 1:18



















    7














    Whenever I start thinking about CORS, my intuition about which site hosts the headers is incorrect, just as you described in your question. For me, it helps to think about the purpose of the same origin policy.



    The purpose of the same origin policy is to protect you from malicious JavaScript on siteA.com accessing private information you've chosen to share only with siteB.com. Without the same origin policy, JavaScript written by the authors of siteA.com could make your browser make requests to siteB.com, using your authentication cookies for siteB.com. In this way, siteA.com could steal the secret information you share with siteB.com.



    Sometimes you need to work cross domain, which is where CORS comes in. CORS relaxes the same origin policy for domainA.com, using the Access-Control-Allow-Origin header to list other domains (domainB.com) that are trusted to run JavaScript that can interact with domainA.com.



    To understand which domain should serve the CORS headers, consider this. You visit malicious.com, which contains some JavaScript that tries to make a cross domain request to mybank.com. It should be up to mybank.com, not malicious.com, to decide whether or not it sets CORS headers that relax the same origin policy allowing the JavaScript from malicious.com to interact with it. If malicous.com could set its own CORS headers allowing its own JavaScript access to mybank.com, this would completely nullify the same origin policy.



    I think the reason for my bad intuition is the point of view I have when developing a site. It's my site, with all my JavaScript, therefore it isn't doing anything malicious and it should be up to me to specify which other sites my JavaScript can interact with. When in fact I should be thinking which other sites JavaScript are trying to interact with my site and should I use CORS to allow them?






    share|improve this answer

































      6














      1. A client downloads javascript code MyCode.js from http://siteA - the origin.



      The code that does the downloading - your html script tag or xhr from javascript or whatever - came from, let's say, http://siteZ. And, when the browser requests MyCode.js, it sends an Origin: header saying "Origin: http://siteZ", because it can see that you're requesting to siteA and siteZ != siteA. (You cannot stop or interfere with this.)



      2. The response header of MyCode.js contains Access-Control-Allow-Origin: http://siteB, which I thought meant that MyCode.js was allowed to make cross-origin references to the site B.



      no. It means, Only siteB is allowed to do this request. So your request for MyCode.js from siteZ gets an error instead, and the browser typically gives you nothing. But if you make your server return A-C-A-O: siteZ instead, you'll get MyCode.js . Or if it sends '*', that'll work, that'll let everybody in. Or if the server always sends the string from the Origin: header... but... for security, if you're afraid of hackers, your server should only allow origins on a shortlist, that are allowed to make those requests.



      Then, MyCode.js comes from siteA. When it makes requests to siteB, they are all cross-origin, the browser sends Origin: siteA, and siteB has to take the siteA, recognize it's on the short list of allowed requesters, and send back A-C-A-O: siteA. Only then will the browser let your script get the result of those requests.






      share|improve this answer































        6














        i work with express 4 and node 7.4 and angular,I had the same problem me help this:

        a) server side: in file app.js i give headers to all response like:



        app.use(function(req, res, next) {  
        res.header('Access-Control-Allow-Origin', req.headers.origin);
        res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
        next();
        });


        this must have before all router.

        I saw a lot of added this headers:



        res.header("Access-Control-Allow-Headers","*");
        res.header('Access-Control-Allow-Credentials', true);
        res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');


        but i dont need that,

        b) client side: in send ajax you need add: "withCredentials: true," like:



        $http({
        method: 'POST',
        url: 'url,
        withCredentials: true,
        data : {}
        }).then(function(response){
        // code
        }, function (response) {
        // code
        });


        good luck.






        share|improve this answer































          3














          If you are using PHP, try to add the following code at the beaning of the php file:



          if you are using localhost, try this:



          header("Access-Control-Allow-Origin: *");


          if you are using external domains such as server, try this:



          header("Access-Control-Allow-Origin: http://www.website.com");





          share|improve this answer































            2














            For cross origin sharing, set header: 'Access-Control-Allow-Origin':'*';



            Php: header('Access-Control-Allow-Origin':'*');



            Node: app.use('Access-Control-Allow-Origin':'*');



            This will allow to share content for different domain.






            share|improve this answer

































              2














              In Python I have been using the Flask-CORS library with great success. It makes dealing with CORS super easy and painless. I added some code from the library's documentation below.



              Installing:



              $ pip install -U flask-cors


              Simple example that allows CORS for all domains on all routes:



              from flask import Flask
              from flask_cors import CORS

              app = Flask(__name__)
              CORS(app)

              @app.route("/")
              def helloWorld():
              return "Hello, cross-origin-world!"


              For more specific examples see the documentation. I have used the simple example above to get around the CORS issue in an ionic application I am building that has to access a separate flask server.






              share|improve this answer































                0














                Simply paste the following code in your web.config file.



                Noted that, you have to paste the following code under <system.webServer> tag



                    <httpProtocol>  
                <customHeaders>
                <add name="Access-Control-Allow-Origin" value="*" />
                <add name="Access-Control-Allow-Headers" value="Content-Type" />
                <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
                </customHeaders>
                </httpProtocol>





                share|improve this answer































                  0















                  The Access-Control-Allow-Origin response header indicates whether the
                  response can be shared with requesting code from the given origin.




                  Header type Response       header
                  Forbidden header name no



                  A response that tells the browser to allow code from any origin to
                  access a resource will include the following:




                  Access-Control-Allow-Origin: *


                  For more info, visit here....






                  share|improve this answer






















                    protected by Community May 16 '17 at 19:30



                    Thank you for your interest in this question.
                    Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).



                    Would you like to answer one of these unanswered questions instead?














                    13 Answers
                    13






                    active

                    oldest

                    votes








                    13 Answers
                    13






                    active

                    oldest

                    votes









                    active

                    oldest

                    votes






                    active

                    oldest

                    votes









                    1141














                    Access-Control-Allow-Origin is a CORS (Cross-Origin Resource Sharing) header.



                    When Site A tries to fetch content from Site B, Site B can send an Access-Control-Allow-Origin response header to tell the browser that the content of this page is accessible to certain origins. (An origin is a domain, plus a scheme and port number.) By default, Site B's pages are not accessible to any other origin; using the Access-Control-Allow-Origin header opens a door for cross-origin access by specific requesting origins.



                    For each resource/page that Site B wants to make accessible to Site A, Site B should serve its pages with the response header:



                    Access-Control-Allow-Origin: http://siteA.com


                    Modern browsers will not block cross-domain requests outright. If Site A requests a page from Site B, the browser will actually fetch the requested page on the network level and check if the response headers list Site A as a permitted requester domain. If Site B has not indicated that Site A is allowed to access this page, the browser will trigger the XMLHttpRequest's error event and deny the response data to the requesting JavaScript code.



                    Non-simple requests



                    What happens on the network level can be slightly more complex than explained above. If the request is a "non-simple" request, the browser first sends a data-less "preflight" OPTIONS request, to verify that the server will accept the request. A request is non-simple when either (or both):




                    • using an HTTP verb other than GET or POST (e.g. PUT, DELETE)

                    • using non-simple request headers; the only simple requests headers are:


                      • Accept

                      • Accept-Language

                      • Content-Language


                      • Content-Type (this is only simple when its value is application/x-www-form-urlencoded, multipart/form-data, or text/plain)




                    If the server responds to the OPTIONS preflight with appropriate response headers (Access-Control-Allow-Headers for non-simple headers, Access-Control-Allow-Methods for non-simple verbs) that match the non-simple verb and/or non-simple headers, then the browser sends the actual request.



                    Supposing that Site A wants to send a PUT request for /somePage, with a non-simple Content-Type value of application/json, the browser would first send a preflight request:



                    OPTIONS /somePage HTTP/1.1
                    Origin: http://siteA.com
                    Access-Control-Request-Method: PUT
                    Access-Control-Request-Headers: Content-Type


                    Note that Access-Control-Request-Method and Access-Control-Request-Headers are added by the browser automatically; you do not need to add them. This OPTIONS preflight gets the successful response headers:



                    Access-Control-Allow-Origin: http://siteA.com
                    Access-Control-Allow-Methods: GET, POST, PUT
                    Access-Control-Allow-Headers: Content-Type


                    When sending the actual request (after preflight is done), the behavior is identical to how a simple request is handled. In other words, a non-simple request whose preflight is successful is treated the same as a simple request (i.e., the server must still send Access-Control-Allow-Origin again for the actual response).



                    The browsers sends the actual request:



                    PUT /somePage HTTP/1.1
                    Origin: http://siteA.com
                    Content-Type: application/json

                    { "myRequestContent": "JSON is so great" }


                    And the server sends back an Access-Control-Allow-Origin, just as it would for a simple request:



                    Access-Control-Allow-Origin: http://siteA.com


                    See Understanding XMLHttpRequest over CORS for a little more information about non-simple requests.






                    share|improve this answer





















                    • 4





                      But MyCode.js cannot reach for site B in the first place! How will this header arrive at the client? BTW, kudos for the light life glider in the avatar.

                      – mark
                      May 17 '12 at 13:36








                    • 5





                      I edited with clarification: the browser actually does perform a network fetch on site B to check the Access-Control-Allow-Origin header, but it might not provide the response to the JS code on site A if the header doesn't allow site A to have it. (P.S. Thanks :) )

                      – apsillers
                      May 17 '12 at 13:41








                    • 2





                      Indeed, I do not see any record of the download in Fiddler, unless the cross-origin request is approved. Interesting...

                      – mark
                      May 17 '12 at 14:18






                    • 14





                      @Jwan622 A fundamental "why?" question like that is probably out of scope for this particular answer, which is just about rules & mechanics. Basically, the browser allows you, the human sitting at the computer, see any resource from any origin. It disallows scripts (which could be written by anyone) from reading resources from origins that are different from the origin of the page running the script. Some related questions are programmers.stackexchange.com/q/216605 and What is the threat model for the same origin policy?

                      – apsillers
                      Jul 12 '15 at 17:55






                    • 2





                      In case of using an authentication, Access-Control-Allow-Origin does not accept the * in some browsers (FF and Chrome AFAIK). So in this case you have to specify the value from the Origin header. Hope that this will help someone.

                      – Zsolti
                      Sep 9 '16 at 19:59
















                    1141














                    Access-Control-Allow-Origin is a CORS (Cross-Origin Resource Sharing) header.



                    When Site A tries to fetch content from Site B, Site B can send an Access-Control-Allow-Origin response header to tell the browser that the content of this page is accessible to certain origins. (An origin is a domain, plus a scheme and port number.) By default, Site B's pages are not accessible to any other origin; using the Access-Control-Allow-Origin header opens a door for cross-origin access by specific requesting origins.



                    For each resource/page that Site B wants to make accessible to Site A, Site B should serve its pages with the response header:



                    Access-Control-Allow-Origin: http://siteA.com


                    Modern browsers will not block cross-domain requests outright. If Site A requests a page from Site B, the browser will actually fetch the requested page on the network level and check if the response headers list Site A as a permitted requester domain. If Site B has not indicated that Site A is allowed to access this page, the browser will trigger the XMLHttpRequest's error event and deny the response data to the requesting JavaScript code.



                    Non-simple requests



                    What happens on the network level can be slightly more complex than explained above. If the request is a "non-simple" request, the browser first sends a data-less "preflight" OPTIONS request, to verify that the server will accept the request. A request is non-simple when either (or both):




                    • using an HTTP verb other than GET or POST (e.g. PUT, DELETE)

                    • using non-simple request headers; the only simple requests headers are:


                      • Accept

                      • Accept-Language

                      • Content-Language


                      • Content-Type (this is only simple when its value is application/x-www-form-urlencoded, multipart/form-data, or text/plain)




                    If the server responds to the OPTIONS preflight with appropriate response headers (Access-Control-Allow-Headers for non-simple headers, Access-Control-Allow-Methods for non-simple verbs) that match the non-simple verb and/or non-simple headers, then the browser sends the actual request.



                    Supposing that Site A wants to send a PUT request for /somePage, with a non-simple Content-Type value of application/json, the browser would first send a preflight request:



                    OPTIONS /somePage HTTP/1.1
                    Origin: http://siteA.com
                    Access-Control-Request-Method: PUT
                    Access-Control-Request-Headers: Content-Type


                    Note that Access-Control-Request-Method and Access-Control-Request-Headers are added by the browser automatically; you do not need to add them. This OPTIONS preflight gets the successful response headers:



                    Access-Control-Allow-Origin: http://siteA.com
                    Access-Control-Allow-Methods: GET, POST, PUT
                    Access-Control-Allow-Headers: Content-Type


                    When sending the actual request (after preflight is done), the behavior is identical to how a simple request is handled. In other words, a non-simple request whose preflight is successful is treated the same as a simple request (i.e., the server must still send Access-Control-Allow-Origin again for the actual response).



                    The browsers sends the actual request:



                    PUT /somePage HTTP/1.1
                    Origin: http://siteA.com
                    Content-Type: application/json

                    { "myRequestContent": "JSON is so great" }


                    And the server sends back an Access-Control-Allow-Origin, just as it would for a simple request:



                    Access-Control-Allow-Origin: http://siteA.com


                    See Understanding XMLHttpRequest over CORS for a little more information about non-simple requests.






                    share|improve this answer





















                    • 4





                      But MyCode.js cannot reach for site B in the first place! How will this header arrive at the client? BTW, kudos for the light life glider in the avatar.

                      – mark
                      May 17 '12 at 13:36








                    • 5





                      I edited with clarification: the browser actually does perform a network fetch on site B to check the Access-Control-Allow-Origin header, but it might not provide the response to the JS code on site A if the header doesn't allow site A to have it. (P.S. Thanks :) )

                      – apsillers
                      May 17 '12 at 13:41








                    • 2





                      Indeed, I do not see any record of the download in Fiddler, unless the cross-origin request is approved. Interesting...

                      – mark
                      May 17 '12 at 14:18






                    • 14





                      @Jwan622 A fundamental "why?" question like that is probably out of scope for this particular answer, which is just about rules & mechanics. Basically, the browser allows you, the human sitting at the computer, see any resource from any origin. It disallows scripts (which could be written by anyone) from reading resources from origins that are different from the origin of the page running the script. Some related questions are programmers.stackexchange.com/q/216605 and What is the threat model for the same origin policy?

                      – apsillers
                      Jul 12 '15 at 17:55






                    • 2





                      In case of using an authentication, Access-Control-Allow-Origin does not accept the * in some browsers (FF and Chrome AFAIK). So in this case you have to specify the value from the Origin header. Hope that this will help someone.

                      – Zsolti
                      Sep 9 '16 at 19:59














                    1141












                    1141








                    1141







                    Access-Control-Allow-Origin is a CORS (Cross-Origin Resource Sharing) header.



                    When Site A tries to fetch content from Site B, Site B can send an Access-Control-Allow-Origin response header to tell the browser that the content of this page is accessible to certain origins. (An origin is a domain, plus a scheme and port number.) By default, Site B's pages are not accessible to any other origin; using the Access-Control-Allow-Origin header opens a door for cross-origin access by specific requesting origins.



                    For each resource/page that Site B wants to make accessible to Site A, Site B should serve its pages with the response header:



                    Access-Control-Allow-Origin: http://siteA.com


                    Modern browsers will not block cross-domain requests outright. If Site A requests a page from Site B, the browser will actually fetch the requested page on the network level and check if the response headers list Site A as a permitted requester domain. If Site B has not indicated that Site A is allowed to access this page, the browser will trigger the XMLHttpRequest's error event and deny the response data to the requesting JavaScript code.



                    Non-simple requests



                    What happens on the network level can be slightly more complex than explained above. If the request is a "non-simple" request, the browser first sends a data-less "preflight" OPTIONS request, to verify that the server will accept the request. A request is non-simple when either (or both):




                    • using an HTTP verb other than GET or POST (e.g. PUT, DELETE)

                    • using non-simple request headers; the only simple requests headers are:


                      • Accept

                      • Accept-Language

                      • Content-Language


                      • Content-Type (this is only simple when its value is application/x-www-form-urlencoded, multipart/form-data, or text/plain)




                    If the server responds to the OPTIONS preflight with appropriate response headers (Access-Control-Allow-Headers for non-simple headers, Access-Control-Allow-Methods for non-simple verbs) that match the non-simple verb and/or non-simple headers, then the browser sends the actual request.



                    Supposing that Site A wants to send a PUT request for /somePage, with a non-simple Content-Type value of application/json, the browser would first send a preflight request:



                    OPTIONS /somePage HTTP/1.1
                    Origin: http://siteA.com
                    Access-Control-Request-Method: PUT
                    Access-Control-Request-Headers: Content-Type


                    Note that Access-Control-Request-Method and Access-Control-Request-Headers are added by the browser automatically; you do not need to add them. This OPTIONS preflight gets the successful response headers:



                    Access-Control-Allow-Origin: http://siteA.com
                    Access-Control-Allow-Methods: GET, POST, PUT
                    Access-Control-Allow-Headers: Content-Type


                    When sending the actual request (after preflight is done), the behavior is identical to how a simple request is handled. In other words, a non-simple request whose preflight is successful is treated the same as a simple request (i.e., the server must still send Access-Control-Allow-Origin again for the actual response).



                    The browsers sends the actual request:



                    PUT /somePage HTTP/1.1
                    Origin: http://siteA.com
                    Content-Type: application/json

                    { "myRequestContent": "JSON is so great" }


                    And the server sends back an Access-Control-Allow-Origin, just as it would for a simple request:



                    Access-Control-Allow-Origin: http://siteA.com


                    See Understanding XMLHttpRequest over CORS for a little more information about non-simple requests.






                    share|improve this answer















                    Access-Control-Allow-Origin is a CORS (Cross-Origin Resource Sharing) header.



                    When Site A tries to fetch content from Site B, Site B can send an Access-Control-Allow-Origin response header to tell the browser that the content of this page is accessible to certain origins. (An origin is a domain, plus a scheme and port number.) By default, Site B's pages are not accessible to any other origin; using the Access-Control-Allow-Origin header opens a door for cross-origin access by specific requesting origins.



                    For each resource/page that Site B wants to make accessible to Site A, Site B should serve its pages with the response header:



                    Access-Control-Allow-Origin: http://siteA.com


                    Modern browsers will not block cross-domain requests outright. If Site A requests a page from Site B, the browser will actually fetch the requested page on the network level and check if the response headers list Site A as a permitted requester domain. If Site B has not indicated that Site A is allowed to access this page, the browser will trigger the XMLHttpRequest's error event and deny the response data to the requesting JavaScript code.



                    Non-simple requests



                    What happens on the network level can be slightly more complex than explained above. If the request is a "non-simple" request, the browser first sends a data-less "preflight" OPTIONS request, to verify that the server will accept the request. A request is non-simple when either (or both):




                    • using an HTTP verb other than GET or POST (e.g. PUT, DELETE)

                    • using non-simple request headers; the only simple requests headers are:


                      • Accept

                      • Accept-Language

                      • Content-Language


                      • Content-Type (this is only simple when its value is application/x-www-form-urlencoded, multipart/form-data, or text/plain)




                    If the server responds to the OPTIONS preflight with appropriate response headers (Access-Control-Allow-Headers for non-simple headers, Access-Control-Allow-Methods for non-simple verbs) that match the non-simple verb and/or non-simple headers, then the browser sends the actual request.



                    Supposing that Site A wants to send a PUT request for /somePage, with a non-simple Content-Type value of application/json, the browser would first send a preflight request:



                    OPTIONS /somePage HTTP/1.1
                    Origin: http://siteA.com
                    Access-Control-Request-Method: PUT
                    Access-Control-Request-Headers: Content-Type


                    Note that Access-Control-Request-Method and Access-Control-Request-Headers are added by the browser automatically; you do not need to add them. This OPTIONS preflight gets the successful response headers:



                    Access-Control-Allow-Origin: http://siteA.com
                    Access-Control-Allow-Methods: GET, POST, PUT
                    Access-Control-Allow-Headers: Content-Type


                    When sending the actual request (after preflight is done), the behavior is identical to how a simple request is handled. In other words, a non-simple request whose preflight is successful is treated the same as a simple request (i.e., the server must still send Access-Control-Allow-Origin again for the actual response).



                    The browsers sends the actual request:



                    PUT /somePage HTTP/1.1
                    Origin: http://siteA.com
                    Content-Type: application/json

                    { "myRequestContent": "JSON is so great" }


                    And the server sends back an Access-Control-Allow-Origin, just as it would for a simple request:



                    Access-Control-Allow-Origin: http://siteA.com


                    See Understanding XMLHttpRequest over CORS for a little more information about non-simple requests.







                    share|improve this answer














                    share|improve this answer



                    share|improve this answer








                    edited May 23 '17 at 11:47









                    Community

                    11




                    11










                    answered May 17 '12 at 13:33









                    apsillersapsillers

                    82.3k9162189




                    82.3k9162189








                    • 4





                      But MyCode.js cannot reach for site B in the first place! How will this header arrive at the client? BTW, kudos for the light life glider in the avatar.

                      – mark
                      May 17 '12 at 13:36








                    • 5





                      I edited with clarification: the browser actually does perform a network fetch on site B to check the Access-Control-Allow-Origin header, but it might not provide the response to the JS code on site A if the header doesn't allow site A to have it. (P.S. Thanks :) )

                      – apsillers
                      May 17 '12 at 13:41








                    • 2





                      Indeed, I do not see any record of the download in Fiddler, unless the cross-origin request is approved. Interesting...

                      – mark
                      May 17 '12 at 14:18






                    • 14





                      @Jwan622 A fundamental "why?" question like that is probably out of scope for this particular answer, which is just about rules & mechanics. Basically, the browser allows you, the human sitting at the computer, see any resource from any origin. It disallows scripts (which could be written by anyone) from reading resources from origins that are different from the origin of the page running the script. Some related questions are programmers.stackexchange.com/q/216605 and What is the threat model for the same origin policy?

                      – apsillers
                      Jul 12 '15 at 17:55






                    • 2





                      In case of using an authentication, Access-Control-Allow-Origin does not accept the * in some browsers (FF and Chrome AFAIK). So in this case you have to specify the value from the Origin header. Hope that this will help someone.

                      – Zsolti
                      Sep 9 '16 at 19:59














                    • 4





                      But MyCode.js cannot reach for site B in the first place! How will this header arrive at the client? BTW, kudos for the light life glider in the avatar.

                      – mark
                      May 17 '12 at 13:36








                    • 5





                      I edited with clarification: the browser actually does perform a network fetch on site B to check the Access-Control-Allow-Origin header, but it might not provide the response to the JS code on site A if the header doesn't allow site A to have it. (P.S. Thanks :) )

                      – apsillers
                      May 17 '12 at 13:41








                    • 2





                      Indeed, I do not see any record of the download in Fiddler, unless the cross-origin request is approved. Interesting...

                      – mark
                      May 17 '12 at 14:18






                    • 14





                      @Jwan622 A fundamental "why?" question like that is probably out of scope for this particular answer, which is just about rules & mechanics. Basically, the browser allows you, the human sitting at the computer, see any resource from any origin. It disallows scripts (which could be written by anyone) from reading resources from origins that are different from the origin of the page running the script. Some related questions are programmers.stackexchange.com/q/216605 and What is the threat model for the same origin policy?

                      – apsillers
                      Jul 12 '15 at 17:55






                    • 2





                      In case of using an authentication, Access-Control-Allow-Origin does not accept the * in some browsers (FF and Chrome AFAIK). So in this case you have to specify the value from the Origin header. Hope that this will help someone.

                      – Zsolti
                      Sep 9 '16 at 19:59








                    4




                    4





                    But MyCode.js cannot reach for site B in the first place! How will this header arrive at the client? BTW, kudos for the light life glider in the avatar.

                    – mark
                    May 17 '12 at 13:36







                    But MyCode.js cannot reach for site B in the first place! How will this header arrive at the client? BTW, kudos for the light life glider in the avatar.

                    – mark
                    May 17 '12 at 13:36






                    5




                    5





                    I edited with clarification: the browser actually does perform a network fetch on site B to check the Access-Control-Allow-Origin header, but it might not provide the response to the JS code on site A if the header doesn't allow site A to have it. (P.S. Thanks :) )

                    – apsillers
                    May 17 '12 at 13:41







                    I edited with clarification: the browser actually does perform a network fetch on site B to check the Access-Control-Allow-Origin header, but it might not provide the response to the JS code on site A if the header doesn't allow site A to have it. (P.S. Thanks :) )

                    – apsillers
                    May 17 '12 at 13:41






                    2




                    2





                    Indeed, I do not see any record of the download in Fiddler, unless the cross-origin request is approved. Interesting...

                    – mark
                    May 17 '12 at 14:18





                    Indeed, I do not see any record of the download in Fiddler, unless the cross-origin request is approved. Interesting...

                    – mark
                    May 17 '12 at 14:18




                    14




                    14





                    @Jwan622 A fundamental "why?" question like that is probably out of scope for this particular answer, which is just about rules & mechanics. Basically, the browser allows you, the human sitting at the computer, see any resource from any origin. It disallows scripts (which could be written by anyone) from reading resources from origins that are different from the origin of the page running the script. Some related questions are programmers.stackexchange.com/q/216605 and What is the threat model for the same origin policy?

                    – apsillers
                    Jul 12 '15 at 17:55





                    @Jwan622 A fundamental "why?" question like that is probably out of scope for this particular answer, which is just about rules & mechanics. Basically, the browser allows you, the human sitting at the computer, see any resource from any origin. It disallows scripts (which could be written by anyone) from reading resources from origins that are different from the origin of the page running the script. Some related questions are programmers.stackexchange.com/q/216605 and What is the threat model for the same origin policy?

                    – apsillers
                    Jul 12 '15 at 17:55




                    2




                    2





                    In case of using an authentication, Access-Control-Allow-Origin does not accept the * in some browsers (FF and Chrome AFAIK). So in this case you have to specify the value from the Origin header. Hope that this will help someone.

                    – Zsolti
                    Sep 9 '16 at 19:59





                    In case of using an authentication, Access-Control-Allow-Origin does not accept the * in some browsers (FF and Chrome AFAIK). So in this case you have to specify the value from the Origin header. Hope that this will help someone.

                    – Zsolti
                    Sep 9 '16 at 19:59













                    107














                    Cross-Origin Request Sharing - CORS (A.K.A. Cross-Domain AJAX request) is an issue that most web developers might encounter, according to Same-Origin-Policy, browsers restrict client JavaScript in a security sandbox, usually JS cannot directly communicate with a remote server from a different domain. In the past developers created many tricky ways to achieve Cross-Domain resource request, most commonly using ways are:




                    1. Use Flash/Silverlight or server side as a "proxy" to communicate
                      with remote.

                    2. JSON With Padding (JSONP).

                    3. Embeds remote server in an iframe and communicate through fragment or window.name, refer here.


                    Those tricky ways have more or less some issues, for example JSONP might result in security hole if developers simply "eval" it, and #3 above, although it works, both domains should build strict contract between each other, it neither flexible nor elegant IMHO:)



                    W3C had introduced Cross-Origin Resource Sharing (CORS) as a standard solution to provide a safe, flexible and a recommended standard way to solve this issue.



                    The Mechanism



                    From a high level we can simply deem CORS is a contract between client AJAX call from domain A and a page hosted on domain B, a typical Cross-Origin request/response would be:



                    DomainA AJAX request headers



                    Host DomainB.com
                    User-Agent Mozilla/5.0 (Windows NT 6.1; WOW64; rv:2.0) Gecko/20100101 Firefox/4.0
                    Accept text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8,application/json
                    Accept-Language en-us;
                    Accept-Encoding gzip, deflate
                    Keep-Alive 115
                    Origin http://DomainA.com


                    DomainB response headers



                    Cache-Control private
                    Content-Type application/json; charset=utf-8
                    Access-Control-Allow-Origin DomainA.com
                    Content-Length 87
                    Proxy-Connection Keep-Alive
                    Connection Keep-Alive


                    The blue parts I marked above were the kernal facts, "Origin" request header "indicates where the cross-origin request or preflight request originates from", the "Access-Control-Allow-Origin" response header indicates this page allows remote request from DomainA (if the value is * indicate allows remote requests from any domain).



                    As I mentioned above, W3 recommended browser to implement a "preflight request" before submiting the actually Cross-Origin HTTP request, in a nutshell it is an HTTP OPTIONS request:



                    OPTIONS DomainB.com/foo.aspx HTTP/1.1


                    If foo.aspx supports OPTIONS HTTP verb, it might return response like below:



                    HTTP/1.1 200 OK
                    Date: Wed, 01 Mar 2011 15:38:19 GMT
                    Access-Control-Allow-Origin: http://DomainA.com
                    Access-Control-Allow-Methods: POST, GET, OPTIONS, HEAD
                    Access-Control-Allow-Headers: X-Requested-With
                    Access-Control-Max-Age: 1728000
                    Connection: Keep-Alive
                    Content-Type: application/json


                    Only if the response contains "Access-Control-Allow-Origin" AND its value is "*" or contain the domain who submitted the CORS request, by satisfying this mandtory condition browser will submit the actual Cross-Domain request, and cache the result in "Preflight-Result-Cache".



                    I blogged about CORS three years ago: AJAX Cross-Origin HTTP request






                    share|improve this answer


























                    • This answer made me realize why i was suddenly getting an issue without using this header for POST and GET requests. I had accidently opened the index.html file directly from disk, so the URL the client was accessing on node.js was thought to be cross-domain, while it was simply running on localhost. Accessing via the URL (as one would usually do) "solved" my issue...

                      – LuqJensen
                      Jan 8 '17 at 21:06











                    • Would a domain in an external network able to communite with a domain on an internal network?

                      – Si8
                      Mar 31 '17 at 1:47
















                    107














                    Cross-Origin Request Sharing - CORS (A.K.A. Cross-Domain AJAX request) is an issue that most web developers might encounter, according to Same-Origin-Policy, browsers restrict client JavaScript in a security sandbox, usually JS cannot directly communicate with a remote server from a different domain. In the past developers created many tricky ways to achieve Cross-Domain resource request, most commonly using ways are:




                    1. Use Flash/Silverlight or server side as a "proxy" to communicate
                      with remote.

                    2. JSON With Padding (JSONP).

                    3. Embeds remote server in an iframe and communicate through fragment or window.name, refer here.


                    Those tricky ways have more or less some issues, for example JSONP might result in security hole if developers simply "eval" it, and #3 above, although it works, both domains should build strict contract between each other, it neither flexible nor elegant IMHO:)



                    W3C had introduced Cross-Origin Resource Sharing (CORS) as a standard solution to provide a safe, flexible and a recommended standard way to solve this issue.



                    The Mechanism



                    From a high level we can simply deem CORS is a contract between client AJAX call from domain A and a page hosted on domain B, a typical Cross-Origin request/response would be:



                    DomainA AJAX request headers



                    Host DomainB.com
                    User-Agent Mozilla/5.0 (Windows NT 6.1; WOW64; rv:2.0) Gecko/20100101 Firefox/4.0
                    Accept text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8,application/json
                    Accept-Language en-us;
                    Accept-Encoding gzip, deflate
                    Keep-Alive 115
                    Origin http://DomainA.com


                    DomainB response headers



                    Cache-Control private
                    Content-Type application/json; charset=utf-8
                    Access-Control-Allow-Origin DomainA.com
                    Content-Length 87
                    Proxy-Connection Keep-Alive
                    Connection Keep-Alive


                    The blue parts I marked above were the kernal facts, "Origin" request header "indicates where the cross-origin request or preflight request originates from", the "Access-Control-Allow-Origin" response header indicates this page allows remote request from DomainA (if the value is * indicate allows remote requests from any domain).



                    As I mentioned above, W3 recommended browser to implement a "preflight request" before submiting the actually Cross-Origin HTTP request, in a nutshell it is an HTTP OPTIONS request:



                    OPTIONS DomainB.com/foo.aspx HTTP/1.1


                    If foo.aspx supports OPTIONS HTTP verb, it might return response like below:



                    HTTP/1.1 200 OK
                    Date: Wed, 01 Mar 2011 15:38:19 GMT
                    Access-Control-Allow-Origin: http://DomainA.com
                    Access-Control-Allow-Methods: POST, GET, OPTIONS, HEAD
                    Access-Control-Allow-Headers: X-Requested-With
                    Access-Control-Max-Age: 1728000
                    Connection: Keep-Alive
                    Content-Type: application/json


                    Only if the response contains "Access-Control-Allow-Origin" AND its value is "*" or contain the domain who submitted the CORS request, by satisfying this mandtory condition browser will submit the actual Cross-Domain request, and cache the result in "Preflight-Result-Cache".



                    I blogged about CORS three years ago: AJAX Cross-Origin HTTP request






                    share|improve this answer


























                    • This answer made me realize why i was suddenly getting an issue without using this header for POST and GET requests. I had accidently opened the index.html file directly from disk, so the URL the client was accessing on node.js was thought to be cross-domain, while it was simply running on localhost. Accessing via the URL (as one would usually do) "solved" my issue...

                      – LuqJensen
                      Jan 8 '17 at 21:06











                    • Would a domain in an external network able to communite with a domain on an internal network?

                      – Si8
                      Mar 31 '17 at 1:47














                    107












                    107








                    107







                    Cross-Origin Request Sharing - CORS (A.K.A. Cross-Domain AJAX request) is an issue that most web developers might encounter, according to Same-Origin-Policy, browsers restrict client JavaScript in a security sandbox, usually JS cannot directly communicate with a remote server from a different domain. In the past developers created many tricky ways to achieve Cross-Domain resource request, most commonly using ways are:




                    1. Use Flash/Silverlight or server side as a "proxy" to communicate
                      with remote.

                    2. JSON With Padding (JSONP).

                    3. Embeds remote server in an iframe and communicate through fragment or window.name, refer here.


                    Those tricky ways have more or less some issues, for example JSONP might result in security hole if developers simply "eval" it, and #3 above, although it works, both domains should build strict contract between each other, it neither flexible nor elegant IMHO:)



                    W3C had introduced Cross-Origin Resource Sharing (CORS) as a standard solution to provide a safe, flexible and a recommended standard way to solve this issue.



                    The Mechanism



                    From a high level we can simply deem CORS is a contract between client AJAX call from domain A and a page hosted on domain B, a typical Cross-Origin request/response would be:



                    DomainA AJAX request headers



                    Host DomainB.com
                    User-Agent Mozilla/5.0 (Windows NT 6.1; WOW64; rv:2.0) Gecko/20100101 Firefox/4.0
                    Accept text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8,application/json
                    Accept-Language en-us;
                    Accept-Encoding gzip, deflate
                    Keep-Alive 115
                    Origin http://DomainA.com


                    DomainB response headers



                    Cache-Control private
                    Content-Type application/json; charset=utf-8
                    Access-Control-Allow-Origin DomainA.com
                    Content-Length 87
                    Proxy-Connection Keep-Alive
                    Connection Keep-Alive


                    The blue parts I marked above were the kernal facts, "Origin" request header "indicates where the cross-origin request or preflight request originates from", the "Access-Control-Allow-Origin" response header indicates this page allows remote request from DomainA (if the value is * indicate allows remote requests from any domain).



                    As I mentioned above, W3 recommended browser to implement a "preflight request" before submiting the actually Cross-Origin HTTP request, in a nutshell it is an HTTP OPTIONS request:



                    OPTIONS DomainB.com/foo.aspx HTTP/1.1


                    If foo.aspx supports OPTIONS HTTP verb, it might return response like below:



                    HTTP/1.1 200 OK
                    Date: Wed, 01 Mar 2011 15:38:19 GMT
                    Access-Control-Allow-Origin: http://DomainA.com
                    Access-Control-Allow-Methods: POST, GET, OPTIONS, HEAD
                    Access-Control-Allow-Headers: X-Requested-With
                    Access-Control-Max-Age: 1728000
                    Connection: Keep-Alive
                    Content-Type: application/json


                    Only if the response contains "Access-Control-Allow-Origin" AND its value is "*" or contain the domain who submitted the CORS request, by satisfying this mandtory condition browser will submit the actual Cross-Domain request, and cache the result in "Preflight-Result-Cache".



                    I blogged about CORS three years ago: AJAX Cross-Origin HTTP request






                    share|improve this answer















                    Cross-Origin Request Sharing - CORS (A.K.A. Cross-Domain AJAX request) is an issue that most web developers might encounter, according to Same-Origin-Policy, browsers restrict client JavaScript in a security sandbox, usually JS cannot directly communicate with a remote server from a different domain. In the past developers created many tricky ways to achieve Cross-Domain resource request, most commonly using ways are:




                    1. Use Flash/Silverlight or server side as a "proxy" to communicate
                      with remote.

                    2. JSON With Padding (JSONP).

                    3. Embeds remote server in an iframe and communicate through fragment or window.name, refer here.


                    Those tricky ways have more or less some issues, for example JSONP might result in security hole if developers simply "eval" it, and #3 above, although it works, both domains should build strict contract between each other, it neither flexible nor elegant IMHO:)



                    W3C had introduced Cross-Origin Resource Sharing (CORS) as a standard solution to provide a safe, flexible and a recommended standard way to solve this issue.



                    The Mechanism



                    From a high level we can simply deem CORS is a contract between client AJAX call from domain A and a page hosted on domain B, a typical Cross-Origin request/response would be:



                    DomainA AJAX request headers



                    Host DomainB.com
                    User-Agent Mozilla/5.0 (Windows NT 6.1; WOW64; rv:2.0) Gecko/20100101 Firefox/4.0
                    Accept text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8,application/json
                    Accept-Language en-us;
                    Accept-Encoding gzip, deflate
                    Keep-Alive 115
                    Origin http://DomainA.com


                    DomainB response headers



                    Cache-Control private
                    Content-Type application/json; charset=utf-8
                    Access-Control-Allow-Origin DomainA.com
                    Content-Length 87
                    Proxy-Connection Keep-Alive
                    Connection Keep-Alive


                    The blue parts I marked above were the kernal facts, "Origin" request header "indicates where the cross-origin request or preflight request originates from", the "Access-Control-Allow-Origin" response header indicates this page allows remote request from DomainA (if the value is * indicate allows remote requests from any domain).



                    As I mentioned above, W3 recommended browser to implement a "preflight request" before submiting the actually Cross-Origin HTTP request, in a nutshell it is an HTTP OPTIONS request:



                    OPTIONS DomainB.com/foo.aspx HTTP/1.1


                    If foo.aspx supports OPTIONS HTTP verb, it might return response like below:



                    HTTP/1.1 200 OK
                    Date: Wed, 01 Mar 2011 15:38:19 GMT
                    Access-Control-Allow-Origin: http://DomainA.com
                    Access-Control-Allow-Methods: POST, GET, OPTIONS, HEAD
                    Access-Control-Allow-Headers: X-Requested-With
                    Access-Control-Max-Age: 1728000
                    Connection: Keep-Alive
                    Content-Type: application/json


                    Only if the response contains "Access-Control-Allow-Origin" AND its value is "*" or contain the domain who submitted the CORS request, by satisfying this mandtory condition browser will submit the actual Cross-Domain request, and cache the result in "Preflight-Result-Cache".



                    I blogged about CORS three years ago: AJAX Cross-Origin HTTP request







                    share|improve this answer














                    share|improve this answer



                    share|improve this answer








                    edited Jul 28 '16 at 9:01









                    Sujania

                    3,07563157




                    3,07563157










                    answered Jan 23 '14 at 13:54









                    Wayne YeWayne Ye

                    1,44221526




                    1,44221526













                    • This answer made me realize why i was suddenly getting an issue without using this header for POST and GET requests. I had accidently opened the index.html file directly from disk, so the URL the client was accessing on node.js was thought to be cross-domain, while it was simply running on localhost. Accessing via the URL (as one would usually do) "solved" my issue...

                      – LuqJensen
                      Jan 8 '17 at 21:06











                    • Would a domain in an external network able to communite with a domain on an internal network?

                      – Si8
                      Mar 31 '17 at 1:47



















                    • This answer made me realize why i was suddenly getting an issue without using this header for POST and GET requests. I had accidently opened the index.html file directly from disk, so the URL the client was accessing on node.js was thought to be cross-domain, while it was simply running on localhost. Accessing via the URL (as one would usually do) "solved" my issue...

                      – LuqJensen
                      Jan 8 '17 at 21:06











                    • Would a domain in an external network able to communite with a domain on an internal network?

                      – Si8
                      Mar 31 '17 at 1:47

















                    This answer made me realize why i was suddenly getting an issue without using this header for POST and GET requests. I had accidently opened the index.html file directly from disk, so the URL the client was accessing on node.js was thought to be cross-domain, while it was simply running on localhost. Accessing via the URL (as one would usually do) "solved" my issue...

                    – LuqJensen
                    Jan 8 '17 at 21:06





                    This answer made me realize why i was suddenly getting an issue without using this header for POST and GET requests. I had accidently opened the index.html file directly from disk, so the URL the client was accessing on node.js was thought to be cross-domain, while it was simply running on localhost. Accessing via the URL (as one would usually do) "solved" my issue...

                    – LuqJensen
                    Jan 8 '17 at 21:06













                    Would a domain in an external network able to communite with a domain on an internal network?

                    – Si8
                    Mar 31 '17 at 1:47





                    Would a domain in an external network able to communite with a domain on an internal network?

                    – Si8
                    Mar 31 '17 at 1:47











                    42














                    Question is a bit too old to answer, but I am posting this for any future reference to this question.



                    According to this Mozilla Developer Network article,




                    A resource makes a cross-origin HTTP request when it requests a resource from a different domain, or port than the one which the first resource itself serves.




                    enter image description here



                    An HTML page served from http://domain-a.com makes an <img> src request for http://domain-b.com/image.jpg.

                    Many pages on the web today load resources like CSS stylesheets, images and scripts from separate domains (thus it should be cool).



                    Same-Origin Policy



                    For security reasons, browsers restrict cross-origin HTTP requests initiated from within scripts.

                    For example, XMLHttpRequest and Fetch follow the same-origin policy.

                    So, a web application using XMLHttpRequest or Fetch could only make HTTP requests to its own domain.



                    Cross-Origin Resource Sharing (CORS)



                    To improve web applications, developers asked browser vendors to allow cross-domain requests.



                    The Cross-Origin Resource Sharing (CORS) mechanism gives web servers cross-domain access controls, which enable secure cross-domain data transfers.

                    Modern browsers use CORS in an API container - such as XMLHttpRequest or Fetch - to mitigate risks of cross-origin HTTP requests.



                    How CORS works (Access-Control-Allow-Origin header)



                    Wikipedia:




                    The CORS standard describes new HTTP headers which provide browsers and servers a way to request remote URLs only when they have permission.



                    Although some validation and authorization can be performed by the server, it is generally the browser's responsibility to support these headers and honor the restrictions they impose.




                    Example





                    1. The browser sends the OPTIONS request with an Origin HTTP header.



                      The value of this header is the domain that served the parent page. When a page from http://www.example.com attempts to access a user's data in service.example.com, the following request header would be sent to service.example.com:



                      Origin: http://www.example.com




                    2. The server at service.example.com may respond with:





                      • An Access-Control-Allow-Origin (ACAO) header in its response indicating which origin sites are allowed.

                        For example:



                        Access-Control-Allow-Origin: http://www.example.com



                      • An error page if the server does not allow the cross-origin request



                      • An Access-Control-Allow-Origin (ACAO) header with a wildcard that allows all domains:



                        Access-Control-Allow-Origin: *










                    share|improve this answer
























                    • How to set none are allowed to acees some thing like Access-Control-Allow-Origin:null

                      – Subin C Poonamgode
                      Aug 25 '17 at 6:18













                    • When I don't want to allow anyone to access my resources through CORS, what value should I set for Access-Control-Allow-Origin ? I mean the negation of Access-Control-Allow-Origin: *

                      – Subin C Poonamgode
                      Aug 31 '17 at 13:54











                    • Just dont set anything, for that purpose

                      – Trix
                      Aug 31 '17 at 13:56
















                    42














                    Question is a bit too old to answer, but I am posting this for any future reference to this question.



                    According to this Mozilla Developer Network article,




                    A resource makes a cross-origin HTTP request when it requests a resource from a different domain, or port than the one which the first resource itself serves.




                    enter image description here



                    An HTML page served from http://domain-a.com makes an <img> src request for http://domain-b.com/image.jpg.

                    Many pages on the web today load resources like CSS stylesheets, images and scripts from separate domains (thus it should be cool).



                    Same-Origin Policy



                    For security reasons, browsers restrict cross-origin HTTP requests initiated from within scripts.

                    For example, XMLHttpRequest and Fetch follow the same-origin policy.

                    So, a web application using XMLHttpRequest or Fetch could only make HTTP requests to its own domain.



                    Cross-Origin Resource Sharing (CORS)



                    To improve web applications, developers asked browser vendors to allow cross-domain requests.



                    The Cross-Origin Resource Sharing (CORS) mechanism gives web servers cross-domain access controls, which enable secure cross-domain data transfers.

                    Modern browsers use CORS in an API container - such as XMLHttpRequest or Fetch - to mitigate risks of cross-origin HTTP requests.



                    How CORS works (Access-Control-Allow-Origin header)



                    Wikipedia:




                    The CORS standard describes new HTTP headers which provide browsers and servers a way to request remote URLs only when they have permission.



                    Although some validation and authorization can be performed by the server, it is generally the browser's responsibility to support these headers and honor the restrictions they impose.




                    Example





                    1. The browser sends the OPTIONS request with an Origin HTTP header.



                      The value of this header is the domain that served the parent page. When a page from http://www.example.com attempts to access a user's data in service.example.com, the following request header would be sent to service.example.com:



                      Origin: http://www.example.com




                    2. The server at service.example.com may respond with:





                      • An Access-Control-Allow-Origin (ACAO) header in its response indicating which origin sites are allowed.

                        For example:



                        Access-Control-Allow-Origin: http://www.example.com



                      • An error page if the server does not allow the cross-origin request



                      • An Access-Control-Allow-Origin (ACAO) header with a wildcard that allows all domains:



                        Access-Control-Allow-Origin: *










                    share|improve this answer
























                    • How to set none are allowed to acees some thing like Access-Control-Allow-Origin:null

                      – Subin C Poonamgode
                      Aug 25 '17 at 6:18













                    • When I don't want to allow anyone to access my resources through CORS, what value should I set for Access-Control-Allow-Origin ? I mean the negation of Access-Control-Allow-Origin: *

                      – Subin C Poonamgode
                      Aug 31 '17 at 13:54











                    • Just dont set anything, for that purpose

                      – Trix
                      Aug 31 '17 at 13:56














                    42












                    42








                    42







                    Question is a bit too old to answer, but I am posting this for any future reference to this question.



                    According to this Mozilla Developer Network article,




                    A resource makes a cross-origin HTTP request when it requests a resource from a different domain, or port than the one which the first resource itself serves.




                    enter image description here



                    An HTML page served from http://domain-a.com makes an <img> src request for http://domain-b.com/image.jpg.

                    Many pages on the web today load resources like CSS stylesheets, images and scripts from separate domains (thus it should be cool).



                    Same-Origin Policy



                    For security reasons, browsers restrict cross-origin HTTP requests initiated from within scripts.

                    For example, XMLHttpRequest and Fetch follow the same-origin policy.

                    So, a web application using XMLHttpRequest or Fetch could only make HTTP requests to its own domain.



                    Cross-Origin Resource Sharing (CORS)



                    To improve web applications, developers asked browser vendors to allow cross-domain requests.



                    The Cross-Origin Resource Sharing (CORS) mechanism gives web servers cross-domain access controls, which enable secure cross-domain data transfers.

                    Modern browsers use CORS in an API container - such as XMLHttpRequest or Fetch - to mitigate risks of cross-origin HTTP requests.



                    How CORS works (Access-Control-Allow-Origin header)



                    Wikipedia:




                    The CORS standard describes new HTTP headers which provide browsers and servers a way to request remote URLs only when they have permission.



                    Although some validation and authorization can be performed by the server, it is generally the browser's responsibility to support these headers and honor the restrictions they impose.




                    Example





                    1. The browser sends the OPTIONS request with an Origin HTTP header.



                      The value of this header is the domain that served the parent page. When a page from http://www.example.com attempts to access a user's data in service.example.com, the following request header would be sent to service.example.com:



                      Origin: http://www.example.com




                    2. The server at service.example.com may respond with:





                      • An Access-Control-Allow-Origin (ACAO) header in its response indicating which origin sites are allowed.

                        For example:



                        Access-Control-Allow-Origin: http://www.example.com



                      • An error page if the server does not allow the cross-origin request



                      • An Access-Control-Allow-Origin (ACAO) header with a wildcard that allows all domains:



                        Access-Control-Allow-Origin: *










                    share|improve this answer













                    Question is a bit too old to answer, but I am posting this for any future reference to this question.



                    According to this Mozilla Developer Network article,




                    A resource makes a cross-origin HTTP request when it requests a resource from a different domain, or port than the one which the first resource itself serves.




                    enter image description here



                    An HTML page served from http://domain-a.com makes an <img> src request for http://domain-b.com/image.jpg.

                    Many pages on the web today load resources like CSS stylesheets, images and scripts from separate domains (thus it should be cool).



                    Same-Origin Policy



                    For security reasons, browsers restrict cross-origin HTTP requests initiated from within scripts.

                    For example, XMLHttpRequest and Fetch follow the same-origin policy.

                    So, a web application using XMLHttpRequest or Fetch could only make HTTP requests to its own domain.



                    Cross-Origin Resource Sharing (CORS)



                    To improve web applications, developers asked browser vendors to allow cross-domain requests.



                    The Cross-Origin Resource Sharing (CORS) mechanism gives web servers cross-domain access controls, which enable secure cross-domain data transfers.

                    Modern browsers use CORS in an API container - such as XMLHttpRequest or Fetch - to mitigate risks of cross-origin HTTP requests.



                    How CORS works (Access-Control-Allow-Origin header)



                    Wikipedia:




                    The CORS standard describes new HTTP headers which provide browsers and servers a way to request remote URLs only when they have permission.



                    Although some validation and authorization can be performed by the server, it is generally the browser's responsibility to support these headers and honor the restrictions they impose.




                    Example





                    1. The browser sends the OPTIONS request with an Origin HTTP header.



                      The value of this header is the domain that served the parent page. When a page from http://www.example.com attempts to access a user's data in service.example.com, the following request header would be sent to service.example.com:



                      Origin: http://www.example.com




                    2. The server at service.example.com may respond with:





                      • An Access-Control-Allow-Origin (ACAO) header in its response indicating which origin sites are allowed.

                        For example:



                        Access-Control-Allow-Origin: http://www.example.com



                      • An error page if the server does not allow the cross-origin request



                      • An Access-Control-Allow-Origin (ACAO) header with a wildcard that allows all domains:



                        Access-Control-Allow-Origin: *











                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Mar 5 '17 at 6:39









                    TrixTrix

                    10k85174




                    10k85174













                    • How to set none are allowed to acees some thing like Access-Control-Allow-Origin:null

                      – Subin C Poonamgode
                      Aug 25 '17 at 6:18













                    • When I don't want to allow anyone to access my resources through CORS, what value should I set for Access-Control-Allow-Origin ? I mean the negation of Access-Control-Allow-Origin: *

                      – Subin C Poonamgode
                      Aug 31 '17 at 13:54











                    • Just dont set anything, for that purpose

                      – Trix
                      Aug 31 '17 at 13:56



















                    • How to set none are allowed to acees some thing like Access-Control-Allow-Origin:null

                      – Subin C Poonamgode
                      Aug 25 '17 at 6:18













                    • When I don't want to allow anyone to access my resources through CORS, what value should I set for Access-Control-Allow-Origin ? I mean the negation of Access-Control-Allow-Origin: *

                      – Subin C Poonamgode
                      Aug 31 '17 at 13:54











                    • Just dont set anything, for that purpose

                      – Trix
                      Aug 31 '17 at 13:56

















                    How to set none are allowed to acees some thing like Access-Control-Allow-Origin:null

                    – Subin C Poonamgode
                    Aug 25 '17 at 6:18







                    How to set none are allowed to acees some thing like Access-Control-Allow-Origin:null

                    – Subin C Poonamgode
                    Aug 25 '17 at 6:18















                    When I don't want to allow anyone to access my resources through CORS, what value should I set for Access-Control-Allow-Origin ? I mean the negation of Access-Control-Allow-Origin: *

                    – Subin C Poonamgode
                    Aug 31 '17 at 13:54





                    When I don't want to allow anyone to access my resources through CORS, what value should I set for Access-Control-Allow-Origin ? I mean the negation of Access-Control-Allow-Origin: *

                    – Subin C Poonamgode
                    Aug 31 '17 at 13:54













                    Just dont set anything, for that purpose

                    – Trix
                    Aug 31 '17 at 13:56





                    Just dont set anything, for that purpose

                    – Trix
                    Aug 31 '17 at 13:56











                    8














                    If you want just to test a cross domain application in which the browser blocks your request, then you can just open your browser in unsafe mode and test your application without changing your code and without making your code unsafe.
                    From MAC OS you can do this from the terminal line:



                    open -a Google Chrome --args --disable-web-security --user-data-dir





                    share|improve this answer




























                      8














                      If you want just to test a cross domain application in which the browser blocks your request, then you can just open your browser in unsafe mode and test your application without changing your code and without making your code unsafe.
                      From MAC OS you can do this from the terminal line:



                      open -a Google Chrome --args --disable-web-security --user-data-dir





                      share|improve this answer


























                        8












                        8








                        8







                        If you want just to test a cross domain application in which the browser blocks your request, then you can just open your browser in unsafe mode and test your application without changing your code and without making your code unsafe.
                        From MAC OS you can do this from the terminal line:



                        open -a Google Chrome --args --disable-web-security --user-data-dir





                        share|improve this answer













                        If you want just to test a cross domain application in which the browser blocks your request, then you can just open your browser in unsafe mode and test your application without changing your code and without making your code unsafe.
                        From MAC OS you can do this from the terminal line:



                        open -a Google Chrome --args --disable-web-security --user-data-dir






                        share|improve this answer












                        share|improve this answer



                        share|improve this answer










                        answered Feb 22 '17 at 16:32









                        Maurizio BrioschiMaurizio Brioschi

                        355612




                        355612























                            7














                            Using React and Axios, join proxy link to the URL and add header as shown below



                            https://cors-anywhere.herokuapp.com/ + Your API URL



                            Just by adding the Proxy link will work, but it can also throw error for No Access again. Hence better to add header as shown below.



                            axios.get(`https://cors-anywhere.herokuapp.com/[YOUR_API_URL]`,{headers: {'Access-Control-Allow-Origin': '*'}})
                            .then(response => console.log(response:data);
                            }





                            share|improve this answer



















                            • 2





                              Please don't do this. Using a proxy link is like handing over user cookies to a middle-man. Should be illegal IMHO

                              – captainserious
                              Dec 9 '17 at 10:12











                            • Thanks for sharing this! You saved my day. You think I can use this hack on production?

                              – blvckasvp
                              Oct 19 '18 at 1:18
















                            7














                            Using React and Axios, join proxy link to the URL and add header as shown below



                            https://cors-anywhere.herokuapp.com/ + Your API URL



                            Just by adding the Proxy link will work, but it can also throw error for No Access again. Hence better to add header as shown below.



                            axios.get(`https://cors-anywhere.herokuapp.com/[YOUR_API_URL]`,{headers: {'Access-Control-Allow-Origin': '*'}})
                            .then(response => console.log(response:data);
                            }





                            share|improve this answer



















                            • 2





                              Please don't do this. Using a proxy link is like handing over user cookies to a middle-man. Should be illegal IMHO

                              – captainserious
                              Dec 9 '17 at 10:12











                            • Thanks for sharing this! You saved my day. You think I can use this hack on production?

                              – blvckasvp
                              Oct 19 '18 at 1:18














                            7












                            7








                            7







                            Using React and Axios, join proxy link to the URL and add header as shown below



                            https://cors-anywhere.herokuapp.com/ + Your API URL



                            Just by adding the Proxy link will work, but it can also throw error for No Access again. Hence better to add header as shown below.



                            axios.get(`https://cors-anywhere.herokuapp.com/[YOUR_API_URL]`,{headers: {'Access-Control-Allow-Origin': '*'}})
                            .then(response => console.log(response:data);
                            }





                            share|improve this answer













                            Using React and Axios, join proxy link to the URL and add header as shown below



                            https://cors-anywhere.herokuapp.com/ + Your API URL



                            Just by adding the Proxy link will work, but it can also throw error for No Access again. Hence better to add header as shown below.



                            axios.get(`https://cors-anywhere.herokuapp.com/[YOUR_API_URL]`,{headers: {'Access-Control-Allow-Origin': '*'}})
                            .then(response => console.log(response:data);
                            }






                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered Oct 16 '17 at 15:53









                            Dhaval JardoshDhaval Jardosh

                            3,65921035




                            3,65921035








                            • 2





                              Please don't do this. Using a proxy link is like handing over user cookies to a middle-man. Should be illegal IMHO

                              – captainserious
                              Dec 9 '17 at 10:12











                            • Thanks for sharing this! You saved my day. You think I can use this hack on production?

                              – blvckasvp
                              Oct 19 '18 at 1:18














                            • 2





                              Please don't do this. Using a proxy link is like handing over user cookies to a middle-man. Should be illegal IMHO

                              – captainserious
                              Dec 9 '17 at 10:12











                            • Thanks for sharing this! You saved my day. You think I can use this hack on production?

                              – blvckasvp
                              Oct 19 '18 at 1:18








                            2




                            2





                            Please don't do this. Using a proxy link is like handing over user cookies to a middle-man. Should be illegal IMHO

                            – captainserious
                            Dec 9 '17 at 10:12





                            Please don't do this. Using a proxy link is like handing over user cookies to a middle-man. Should be illegal IMHO

                            – captainserious
                            Dec 9 '17 at 10:12













                            Thanks for sharing this! You saved my day. You think I can use this hack on production?

                            – blvckasvp
                            Oct 19 '18 at 1:18





                            Thanks for sharing this! You saved my day. You think I can use this hack on production?

                            – blvckasvp
                            Oct 19 '18 at 1:18











                            7














                            Whenever I start thinking about CORS, my intuition about which site hosts the headers is incorrect, just as you described in your question. For me, it helps to think about the purpose of the same origin policy.



                            The purpose of the same origin policy is to protect you from malicious JavaScript on siteA.com accessing private information you've chosen to share only with siteB.com. Without the same origin policy, JavaScript written by the authors of siteA.com could make your browser make requests to siteB.com, using your authentication cookies for siteB.com. In this way, siteA.com could steal the secret information you share with siteB.com.



                            Sometimes you need to work cross domain, which is where CORS comes in. CORS relaxes the same origin policy for domainA.com, using the Access-Control-Allow-Origin header to list other domains (domainB.com) that are trusted to run JavaScript that can interact with domainA.com.



                            To understand which domain should serve the CORS headers, consider this. You visit malicious.com, which contains some JavaScript that tries to make a cross domain request to mybank.com. It should be up to mybank.com, not malicious.com, to decide whether or not it sets CORS headers that relax the same origin policy allowing the JavaScript from malicious.com to interact with it. If malicous.com could set its own CORS headers allowing its own JavaScript access to mybank.com, this would completely nullify the same origin policy.



                            I think the reason for my bad intuition is the point of view I have when developing a site. It's my site, with all my JavaScript, therefore it isn't doing anything malicious and it should be up to me to specify which other sites my JavaScript can interact with. When in fact I should be thinking which other sites JavaScript are trying to interact with my site and should I use CORS to allow them?






                            share|improve this answer






























                              7














                              Whenever I start thinking about CORS, my intuition about which site hosts the headers is incorrect, just as you described in your question. For me, it helps to think about the purpose of the same origin policy.



                              The purpose of the same origin policy is to protect you from malicious JavaScript on siteA.com accessing private information you've chosen to share only with siteB.com. Without the same origin policy, JavaScript written by the authors of siteA.com could make your browser make requests to siteB.com, using your authentication cookies for siteB.com. In this way, siteA.com could steal the secret information you share with siteB.com.



                              Sometimes you need to work cross domain, which is where CORS comes in. CORS relaxes the same origin policy for domainA.com, using the Access-Control-Allow-Origin header to list other domains (domainB.com) that are trusted to run JavaScript that can interact with domainA.com.



                              To understand which domain should serve the CORS headers, consider this. You visit malicious.com, which contains some JavaScript that tries to make a cross domain request to mybank.com. It should be up to mybank.com, not malicious.com, to decide whether or not it sets CORS headers that relax the same origin policy allowing the JavaScript from malicious.com to interact with it. If malicous.com could set its own CORS headers allowing its own JavaScript access to mybank.com, this would completely nullify the same origin policy.



                              I think the reason for my bad intuition is the point of view I have when developing a site. It's my site, with all my JavaScript, therefore it isn't doing anything malicious and it should be up to me to specify which other sites my JavaScript can interact with. When in fact I should be thinking which other sites JavaScript are trying to interact with my site and should I use CORS to allow them?






                              share|improve this answer




























                                7












                                7








                                7







                                Whenever I start thinking about CORS, my intuition about which site hosts the headers is incorrect, just as you described in your question. For me, it helps to think about the purpose of the same origin policy.



                                The purpose of the same origin policy is to protect you from malicious JavaScript on siteA.com accessing private information you've chosen to share only with siteB.com. Without the same origin policy, JavaScript written by the authors of siteA.com could make your browser make requests to siteB.com, using your authentication cookies for siteB.com. In this way, siteA.com could steal the secret information you share with siteB.com.



                                Sometimes you need to work cross domain, which is where CORS comes in. CORS relaxes the same origin policy for domainA.com, using the Access-Control-Allow-Origin header to list other domains (domainB.com) that are trusted to run JavaScript that can interact with domainA.com.



                                To understand which domain should serve the CORS headers, consider this. You visit malicious.com, which contains some JavaScript that tries to make a cross domain request to mybank.com. It should be up to mybank.com, not malicious.com, to decide whether or not it sets CORS headers that relax the same origin policy allowing the JavaScript from malicious.com to interact with it. If malicous.com could set its own CORS headers allowing its own JavaScript access to mybank.com, this would completely nullify the same origin policy.



                                I think the reason for my bad intuition is the point of view I have when developing a site. It's my site, with all my JavaScript, therefore it isn't doing anything malicious and it should be up to me to specify which other sites my JavaScript can interact with. When in fact I should be thinking which other sites JavaScript are trying to interact with my site and should I use CORS to allow them?






                                share|improve this answer















                                Whenever I start thinking about CORS, my intuition about which site hosts the headers is incorrect, just as you described in your question. For me, it helps to think about the purpose of the same origin policy.



                                The purpose of the same origin policy is to protect you from malicious JavaScript on siteA.com accessing private information you've chosen to share only with siteB.com. Without the same origin policy, JavaScript written by the authors of siteA.com could make your browser make requests to siteB.com, using your authentication cookies for siteB.com. In this way, siteA.com could steal the secret information you share with siteB.com.



                                Sometimes you need to work cross domain, which is where CORS comes in. CORS relaxes the same origin policy for domainA.com, using the Access-Control-Allow-Origin header to list other domains (domainB.com) that are trusted to run JavaScript that can interact with domainA.com.



                                To understand which domain should serve the CORS headers, consider this. You visit malicious.com, which contains some JavaScript that tries to make a cross domain request to mybank.com. It should be up to mybank.com, not malicious.com, to decide whether or not it sets CORS headers that relax the same origin policy allowing the JavaScript from malicious.com to interact with it. If malicous.com could set its own CORS headers allowing its own JavaScript access to mybank.com, this would completely nullify the same origin policy.



                                I think the reason for my bad intuition is the point of view I have when developing a site. It's my site, with all my JavaScript, therefore it isn't doing anything malicious and it should be up to me to specify which other sites my JavaScript can interact with. When in fact I should be thinking which other sites JavaScript are trying to interact with my site and should I use CORS to allow them?







                                share|improve this answer














                                share|improve this answer



                                share|improve this answer








                                edited Nov 26 '18 at 6:26









                                Eureka

                                647311




                                647311










                                answered Jan 28 '18 at 18:47









                                DomDom

                                1,29221426




                                1,29221426























                                    6














                                    1. A client downloads javascript code MyCode.js from http://siteA - the origin.



                                    The code that does the downloading - your html script tag or xhr from javascript or whatever - came from, let's say, http://siteZ. And, when the browser requests MyCode.js, it sends an Origin: header saying "Origin: http://siteZ", because it can see that you're requesting to siteA and siteZ != siteA. (You cannot stop or interfere with this.)



                                    2. The response header of MyCode.js contains Access-Control-Allow-Origin: http://siteB, which I thought meant that MyCode.js was allowed to make cross-origin references to the site B.



                                    no. It means, Only siteB is allowed to do this request. So your request for MyCode.js from siteZ gets an error instead, and the browser typically gives you nothing. But if you make your server return A-C-A-O: siteZ instead, you'll get MyCode.js . Or if it sends '*', that'll work, that'll let everybody in. Or if the server always sends the string from the Origin: header... but... for security, if you're afraid of hackers, your server should only allow origins on a shortlist, that are allowed to make those requests.



                                    Then, MyCode.js comes from siteA. When it makes requests to siteB, they are all cross-origin, the browser sends Origin: siteA, and siteB has to take the siteA, recognize it's on the short list of allowed requesters, and send back A-C-A-O: siteA. Only then will the browser let your script get the result of those requests.






                                    share|improve this answer




























                                      6














                                      1. A client downloads javascript code MyCode.js from http://siteA - the origin.



                                      The code that does the downloading - your html script tag or xhr from javascript or whatever - came from, let's say, http://siteZ. And, when the browser requests MyCode.js, it sends an Origin: header saying "Origin: http://siteZ", because it can see that you're requesting to siteA and siteZ != siteA. (You cannot stop or interfere with this.)



                                      2. The response header of MyCode.js contains Access-Control-Allow-Origin: http://siteB, which I thought meant that MyCode.js was allowed to make cross-origin references to the site B.



                                      no. It means, Only siteB is allowed to do this request. So your request for MyCode.js from siteZ gets an error instead, and the browser typically gives you nothing. But if you make your server return A-C-A-O: siteZ instead, you'll get MyCode.js . Or if it sends '*', that'll work, that'll let everybody in. Or if the server always sends the string from the Origin: header... but... for security, if you're afraid of hackers, your server should only allow origins on a shortlist, that are allowed to make those requests.



                                      Then, MyCode.js comes from siteA. When it makes requests to siteB, they are all cross-origin, the browser sends Origin: siteA, and siteB has to take the siteA, recognize it's on the short list of allowed requesters, and send back A-C-A-O: siteA. Only then will the browser let your script get the result of those requests.






                                      share|improve this answer


























                                        6












                                        6








                                        6







                                        1. A client downloads javascript code MyCode.js from http://siteA - the origin.



                                        The code that does the downloading - your html script tag or xhr from javascript or whatever - came from, let's say, http://siteZ. And, when the browser requests MyCode.js, it sends an Origin: header saying "Origin: http://siteZ", because it can see that you're requesting to siteA and siteZ != siteA. (You cannot stop or interfere with this.)



                                        2. The response header of MyCode.js contains Access-Control-Allow-Origin: http://siteB, which I thought meant that MyCode.js was allowed to make cross-origin references to the site B.



                                        no. It means, Only siteB is allowed to do this request. So your request for MyCode.js from siteZ gets an error instead, and the browser typically gives you nothing. But if you make your server return A-C-A-O: siteZ instead, you'll get MyCode.js . Or if it sends '*', that'll work, that'll let everybody in. Or if the server always sends the string from the Origin: header... but... for security, if you're afraid of hackers, your server should only allow origins on a shortlist, that are allowed to make those requests.



                                        Then, MyCode.js comes from siteA. When it makes requests to siteB, they are all cross-origin, the browser sends Origin: siteA, and siteB has to take the siteA, recognize it's on the short list of allowed requesters, and send back A-C-A-O: siteA. Only then will the browser let your script get the result of those requests.






                                        share|improve this answer













                                        1. A client downloads javascript code MyCode.js from http://siteA - the origin.



                                        The code that does the downloading - your html script tag or xhr from javascript or whatever - came from, let's say, http://siteZ. And, when the browser requests MyCode.js, it sends an Origin: header saying "Origin: http://siteZ", because it can see that you're requesting to siteA and siteZ != siteA. (You cannot stop or interfere with this.)



                                        2. The response header of MyCode.js contains Access-Control-Allow-Origin: http://siteB, which I thought meant that MyCode.js was allowed to make cross-origin references to the site B.



                                        no. It means, Only siteB is allowed to do this request. So your request for MyCode.js from siteZ gets an error instead, and the browser typically gives you nothing. But if you make your server return A-C-A-O: siteZ instead, you'll get MyCode.js . Or if it sends '*', that'll work, that'll let everybody in. Or if the server always sends the string from the Origin: header... but... for security, if you're afraid of hackers, your server should only allow origins on a shortlist, that are allowed to make those requests.



                                        Then, MyCode.js comes from siteA. When it makes requests to siteB, they are all cross-origin, the browser sends Origin: siteA, and siteB has to take the siteA, recognize it's on the short list of allowed requesters, and send back A-C-A-O: siteA. Only then will the browser let your script get the result of those requests.







                                        share|improve this answer












                                        share|improve this answer



                                        share|improve this answer










                                        answered Feb 27 '16 at 1:37









                                        OsamaBinLoginOsamaBinLogin

                                        15317




                                        15317























                                            6














                                            i work with express 4 and node 7.4 and angular,I had the same problem me help this:

                                            a) server side: in file app.js i give headers to all response like:



                                            app.use(function(req, res, next) {  
                                            res.header('Access-Control-Allow-Origin', req.headers.origin);
                                            res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
                                            next();
                                            });


                                            this must have before all router.

                                            I saw a lot of added this headers:



                                            res.header("Access-Control-Allow-Headers","*");
                                            res.header('Access-Control-Allow-Credentials', true);
                                            res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');


                                            but i dont need that,

                                            b) client side: in send ajax you need add: "withCredentials: true," like:



                                            $http({
                                            method: 'POST',
                                            url: 'url,
                                            withCredentials: true,
                                            data : {}
                                            }).then(function(response){
                                            // code
                                            }, function (response) {
                                            // code
                                            });


                                            good luck.






                                            share|improve this answer




























                                              6














                                              i work with express 4 and node 7.4 and angular,I had the same problem me help this:

                                              a) server side: in file app.js i give headers to all response like:



                                              app.use(function(req, res, next) {  
                                              res.header('Access-Control-Allow-Origin', req.headers.origin);
                                              res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
                                              next();
                                              });


                                              this must have before all router.

                                              I saw a lot of added this headers:



                                              res.header("Access-Control-Allow-Headers","*");
                                              res.header('Access-Control-Allow-Credentials', true);
                                              res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');


                                              but i dont need that,

                                              b) client side: in send ajax you need add: "withCredentials: true," like:



                                              $http({
                                              method: 'POST',
                                              url: 'url,
                                              withCredentials: true,
                                              data : {}
                                              }).then(function(response){
                                              // code
                                              }, function (response) {
                                              // code
                                              });


                                              good luck.






                                              share|improve this answer


























                                                6












                                                6








                                                6







                                                i work with express 4 and node 7.4 and angular,I had the same problem me help this:

                                                a) server side: in file app.js i give headers to all response like:



                                                app.use(function(req, res, next) {  
                                                res.header('Access-Control-Allow-Origin', req.headers.origin);
                                                res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
                                                next();
                                                });


                                                this must have before all router.

                                                I saw a lot of added this headers:



                                                res.header("Access-Control-Allow-Headers","*");
                                                res.header('Access-Control-Allow-Credentials', true);
                                                res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');


                                                but i dont need that,

                                                b) client side: in send ajax you need add: "withCredentials: true," like:



                                                $http({
                                                method: 'POST',
                                                url: 'url,
                                                withCredentials: true,
                                                data : {}
                                                }).then(function(response){
                                                // code
                                                }, function (response) {
                                                // code
                                                });


                                                good luck.






                                                share|improve this answer













                                                i work with express 4 and node 7.4 and angular,I had the same problem me help this:

                                                a) server side: in file app.js i give headers to all response like:



                                                app.use(function(req, res, next) {  
                                                res.header('Access-Control-Allow-Origin', req.headers.origin);
                                                res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
                                                next();
                                                });


                                                this must have before all router.

                                                I saw a lot of added this headers:



                                                res.header("Access-Control-Allow-Headers","*");
                                                res.header('Access-Control-Allow-Credentials', true);
                                                res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');


                                                but i dont need that,

                                                b) client side: in send ajax you need add: "withCredentials: true," like:



                                                $http({
                                                method: 'POST',
                                                url: 'url,
                                                withCredentials: true,
                                                data : {}
                                                }).then(function(response){
                                                // code
                                                }, function (response) {
                                                // code
                                                });


                                                good luck.







                                                share|improve this answer












                                                share|improve this answer



                                                share|improve this answer










                                                answered Feb 6 '17 at 8:19









                                                izik fizik f

                                                79596




                                                79596























                                                    3














                                                    If you are using PHP, try to add the following code at the beaning of the php file:



                                                    if you are using localhost, try this:



                                                    header("Access-Control-Allow-Origin: *");


                                                    if you are using external domains such as server, try this:



                                                    header("Access-Control-Allow-Origin: http://www.website.com");





                                                    share|improve this answer




























                                                      3














                                                      If you are using PHP, try to add the following code at the beaning of the php file:



                                                      if you are using localhost, try this:



                                                      header("Access-Control-Allow-Origin: *");


                                                      if you are using external domains such as server, try this:



                                                      header("Access-Control-Allow-Origin: http://www.website.com");





                                                      share|improve this answer


























                                                        3












                                                        3








                                                        3







                                                        If you are using PHP, try to add the following code at the beaning of the php file:



                                                        if you are using localhost, try this:



                                                        header("Access-Control-Allow-Origin: *");


                                                        if you are using external domains such as server, try this:



                                                        header("Access-Control-Allow-Origin: http://www.website.com");





                                                        share|improve this answer













                                                        If you are using PHP, try to add the following code at the beaning of the php file:



                                                        if you are using localhost, try this:



                                                        header("Access-Control-Allow-Origin: *");


                                                        if you are using external domains such as server, try this:



                                                        header("Access-Control-Allow-Origin: http://www.website.com");






                                                        share|improve this answer












                                                        share|improve this answer



                                                        share|improve this answer










                                                        answered Jan 18 '17 at 15:30









                                                        Melvin GuerreroMelvin Guerrero

                                                        7516




                                                        7516























                                                            2














                                                            For cross origin sharing, set header: 'Access-Control-Allow-Origin':'*';



                                                            Php: header('Access-Control-Allow-Origin':'*');



                                                            Node: app.use('Access-Control-Allow-Origin':'*');



                                                            This will allow to share content for different domain.






                                                            share|improve this answer






























                                                              2














                                                              For cross origin sharing, set header: 'Access-Control-Allow-Origin':'*';



                                                              Php: header('Access-Control-Allow-Origin':'*');



                                                              Node: app.use('Access-Control-Allow-Origin':'*');



                                                              This will allow to share content for different domain.






                                                              share|improve this answer




























                                                                2












                                                                2








                                                                2







                                                                For cross origin sharing, set header: 'Access-Control-Allow-Origin':'*';



                                                                Php: header('Access-Control-Allow-Origin':'*');



                                                                Node: app.use('Access-Control-Allow-Origin':'*');



                                                                This will allow to share content for different domain.






                                                                share|improve this answer















                                                                For cross origin sharing, set header: 'Access-Control-Allow-Origin':'*';



                                                                Php: header('Access-Control-Allow-Origin':'*');



                                                                Node: app.use('Access-Control-Allow-Origin':'*');



                                                                This will allow to share content for different domain.







                                                                share|improve this answer














                                                                share|improve this answer



                                                                share|improve this answer








                                                                edited Jan 16 '17 at 8:10









                                                                budidino

                                                                5,97155866




                                                                5,97155866










                                                                answered Nov 28 '16 at 2:39









                                                                suryadevsuryadev

                                                                732




                                                                732























                                                                    2














                                                                    In Python I have been using the Flask-CORS library with great success. It makes dealing with CORS super easy and painless. I added some code from the library's documentation below.



                                                                    Installing:



                                                                    $ pip install -U flask-cors


                                                                    Simple example that allows CORS for all domains on all routes:



                                                                    from flask import Flask
                                                                    from flask_cors import CORS

                                                                    app = Flask(__name__)
                                                                    CORS(app)

                                                                    @app.route("/")
                                                                    def helloWorld():
                                                                    return "Hello, cross-origin-world!"


                                                                    For more specific examples see the documentation. I have used the simple example above to get around the CORS issue in an ionic application I am building that has to access a separate flask server.






                                                                    share|improve this answer




























                                                                      2














                                                                      In Python I have been using the Flask-CORS library with great success. It makes dealing with CORS super easy and painless. I added some code from the library's documentation below.



                                                                      Installing:



                                                                      $ pip install -U flask-cors


                                                                      Simple example that allows CORS for all domains on all routes:



                                                                      from flask import Flask
                                                                      from flask_cors import CORS

                                                                      app = Flask(__name__)
                                                                      CORS(app)

                                                                      @app.route("/")
                                                                      def helloWorld():
                                                                      return "Hello, cross-origin-world!"


                                                                      For more specific examples see the documentation. I have used the simple example above to get around the CORS issue in an ionic application I am building that has to access a separate flask server.






                                                                      share|improve this answer


























                                                                        2












                                                                        2








                                                                        2







                                                                        In Python I have been using the Flask-CORS library with great success. It makes dealing with CORS super easy and painless. I added some code from the library's documentation below.



                                                                        Installing:



                                                                        $ pip install -U flask-cors


                                                                        Simple example that allows CORS for all domains on all routes:



                                                                        from flask import Flask
                                                                        from flask_cors import CORS

                                                                        app = Flask(__name__)
                                                                        CORS(app)

                                                                        @app.route("/")
                                                                        def helloWorld():
                                                                        return "Hello, cross-origin-world!"


                                                                        For more specific examples see the documentation. I have used the simple example above to get around the CORS issue in an ionic application I am building that has to access a separate flask server.






                                                                        share|improve this answer













                                                                        In Python I have been using the Flask-CORS library with great success. It makes dealing with CORS super easy and painless. I added some code from the library's documentation below.



                                                                        Installing:



                                                                        $ pip install -U flask-cors


                                                                        Simple example that allows CORS for all domains on all routes:



                                                                        from flask import Flask
                                                                        from flask_cors import CORS

                                                                        app = Flask(__name__)
                                                                        CORS(app)

                                                                        @app.route("/")
                                                                        def helloWorld():
                                                                        return "Hello, cross-origin-world!"


                                                                        For more specific examples see the documentation. I have used the simple example above to get around the CORS issue in an ionic application I am building that has to access a separate flask server.







                                                                        share|improve this answer












                                                                        share|improve this answer



                                                                        share|improve this answer










                                                                        answered Jan 25 '18 at 11:10









                                                                        agaidisagaidis

                                                                        694823




                                                                        694823























                                                                            0














                                                                            Simply paste the following code in your web.config file.



                                                                            Noted that, you have to paste the following code under <system.webServer> tag



                                                                                <httpProtocol>  
                                                                            <customHeaders>
                                                                            <add name="Access-Control-Allow-Origin" value="*" />
                                                                            <add name="Access-Control-Allow-Headers" value="Content-Type" />
                                                                            <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
                                                                            </customHeaders>
                                                                            </httpProtocol>





                                                                            share|improve this answer




























                                                                              0














                                                                              Simply paste the following code in your web.config file.



                                                                              Noted that, you have to paste the following code under <system.webServer> tag



                                                                                  <httpProtocol>  
                                                                              <customHeaders>
                                                                              <add name="Access-Control-Allow-Origin" value="*" />
                                                                              <add name="Access-Control-Allow-Headers" value="Content-Type" />
                                                                              <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
                                                                              </customHeaders>
                                                                              </httpProtocol>





                                                                              share|improve this answer


























                                                                                0












                                                                                0








                                                                                0







                                                                                Simply paste the following code in your web.config file.



                                                                                Noted that, you have to paste the following code under <system.webServer> tag



                                                                                    <httpProtocol>  
                                                                                <customHeaders>
                                                                                <add name="Access-Control-Allow-Origin" value="*" />
                                                                                <add name="Access-Control-Allow-Headers" value="Content-Type" />
                                                                                <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
                                                                                </customHeaders>
                                                                                </httpProtocol>





                                                                                share|improve this answer













                                                                                Simply paste the following code in your web.config file.



                                                                                Noted that, you have to paste the following code under <system.webServer> tag



                                                                                    <httpProtocol>  
                                                                                <customHeaders>
                                                                                <add name="Access-Control-Allow-Origin" value="*" />
                                                                                <add name="Access-Control-Allow-Headers" value="Content-Type" />
                                                                                <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
                                                                                </customHeaders>
                                                                                </httpProtocol>






                                                                                share|improve this answer












                                                                                share|improve this answer



                                                                                share|improve this answer










                                                                                answered Jan 20 at 4:35









                                                                                Juboraj SarkerJuboraj Sarker

                                                                                5041411




                                                                                5041411























                                                                                    0















                                                                                    The Access-Control-Allow-Origin response header indicates whether the
                                                                                    response can be shared with requesting code from the given origin.




                                                                                    Header type Response       header
                                                                                    Forbidden header name no



                                                                                    A response that tells the browser to allow code from any origin to
                                                                                    access a resource will include the following:




                                                                                    Access-Control-Allow-Origin: *


                                                                                    For more info, visit here....






                                                                                    share|improve this answer




























                                                                                      0















                                                                                      The Access-Control-Allow-Origin response header indicates whether the
                                                                                      response can be shared with requesting code from the given origin.




                                                                                      Header type Response       header
                                                                                      Forbidden header name no



                                                                                      A response that tells the browser to allow code from any origin to
                                                                                      access a resource will include the following:




                                                                                      Access-Control-Allow-Origin: *


                                                                                      For more info, visit here....






                                                                                      share|improve this answer


























                                                                                        0












                                                                                        0








                                                                                        0








                                                                                        The Access-Control-Allow-Origin response header indicates whether the
                                                                                        response can be shared with requesting code from the given origin.




                                                                                        Header type Response       header
                                                                                        Forbidden header name no



                                                                                        A response that tells the browser to allow code from any origin to
                                                                                        access a resource will include the following:




                                                                                        Access-Control-Allow-Origin: *


                                                                                        For more info, visit here....






                                                                                        share|improve this answer














                                                                                        The Access-Control-Allow-Origin response header indicates whether the
                                                                                        response can be shared with requesting code from the given origin.




                                                                                        Header type Response       header
                                                                                        Forbidden header name no



                                                                                        A response that tells the browser to allow code from any origin to
                                                                                        access a resource will include the following:




                                                                                        Access-Control-Allow-Origin: *


                                                                                        For more info, visit here....







                                                                                        share|improve this answer












                                                                                        share|improve this answer



                                                                                        share|improve this answer










                                                                                        answered Jan 31 at 11:49









                                                                                        AlirezaAlireza

                                                                                        49.4k13173122




                                                                                        49.4k13173122

















                                                                                            protected by Community May 16 '17 at 19:30



                                                                                            Thank you for your interest in this question.
                                                                                            Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).



                                                                                            Would you like to answer one of these unanswered questions instead?



                                                                                            Popular posts from this blog

                                                                                            Ottavio Pratesi

                                                                                            Tricia Helfer

                                                                                            15 giugno