7

I'm having troubles with collecting json values from a URL in my application. When I try to get them a error log is displayed in the console saying that origin is not allowed by access-control-allow-origin.

I researched a bit and found out that response headers have to be set to Access-Control-Allow-Origin: *

How can I do that using pure javascript? No jquery or any other library.

This is my current code:

<script type="text/javascript">
    var xmlHttp = null;
    xmlHttp = new XMLHttpRequest();
    xmlHttp.open( "GET", "http://example.com/id=69", false );
    xmlHttp.send( null );
    console.log("JSON values from URL: ");
    console.log(xmlHttp.responseText);
</script>
Marko Ćilimković
  • 734
  • 1
  • 8
  • 22

2 Answers2

6

I researched a bit and found out that response headers have to be set to Access-Control-Allow-Origin: *

How can I do that using pure javascript? No jquery or any other library.

You can't, not unless your server is running JavaScript (NodeJS, etc.).

The server has to allow access to the resource from the origin of your document. The way it works is:

  • The browser asks permission to access the resource (this is called a "preflight" request), telling the server what resource it wants access to, etc.

  • The server replies with the appropriate headers telling the browser whether access will be allowed.

  • The browser sends the actual request.

  • The server responds to it (again including the relevant headers).

I believe there are situations where the pre-flight isn't necessary. All of that is handled for you by the XMLHttpRequest object.

Details in the Cross-Origin Resource Sharing specification.

Community
  • 1
  • 1
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • My server is running NodeJS. Can I set the response headers then? – Marko Ćilimković Aug 01 '13 at 09:28
  • 1
    @MarkoĆilimković: Of course, in code on the server using [`response.setHeader`](http://nodejs.org/api/http.html#http_response_setheader_name_value). CORS is pretty finicky, you need to be sure you're allowing everything the client is asking for, which means examining the request headers the browser sent. – T.J. Crowder Aug 01 '13 at 09:32
  • @T.J.Crowder this browser extension resolves CORS policy issue on client side . how it can be done without extension https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi?hl=en-US – Satinderpal Singh Sep 03 '18 at 04:21
  • @T.J.Crowder i mean the extension is also using the javascript on client-side but still able to override the CORS issues. So, why it can't be done using javaScript in html page. – Satinderpal Singh Sep 03 '18 at 06:13
  • @SatinderBajwa - Because extensions can do things web-page code can't. – T.J. Crowder Sep 03 '18 at 06:38
3

You cannot do this on client side, your server must send these headers.

mguimard
  • 1,881
  • 13
  • 14