Setting response header using javascript

I'm having problems collecting json values ​​from a url in my application. When I try to get them, an error message is displayed on the console indicating that the origin is not allowed using the access-allow-allow-origin permission.

I did a little research and found out that the response headers should be set in Access-Control-Allow-Origin: *

How can I do this 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> 
+4
source share
2 answers

I did a little research and found out that the response headers should be set in Access-Control-Allow-Origin: *

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

You cannot, unless the server is running JavaScript (NodeJS, etc.).

The server must allow access to the resource from the source of your document. How it works:

  • The browser requests permission to access the resource (this is called a pre-sale request), telling the server which resource it wants to access, etc.

  • The server responds with appropriate headers telling the browser whether access is allowed.

  • The browser sends the actual request.

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

I believe that there are situations when a preliminary flight is not needed. All this is processed for you by the XMLHttpRequest object.

See the Cross-Origin Resource Sharing Specification for details.

+5
source

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

+2
source

Source: https://habr.com/ru/post/1494680/


All Articles