-1

Im trying to get some data from the server, but my request returns me this error: Request header field Access-Control-Allow-Origin is not allowed by Access-Control-Allow-Headers in preflight response.

I tried to solve it, by finding some examples here at stackoverflow, but in my case none of the solutions doesnt seems to work.

Here is my code so far:

    var xhttp = new XMLHttpRequest();
    xhttp.open("GET", "http://api.admin.wobbl.io/policy/preview?id=41", true);
    xhttp.setRequestHeader("Access-Control-Allow-Origin", "*");
    xhttp.setRequestHeader("Access-Control-Allow-Credentials", "true");
    xhttp.setRequestHeader("Access-Control-Allow-Methods", "GET,HEAD,OPTIONS,POST,PUT");
    xhttp.setRequestHeader("Access-Control-Allow-Headers", "Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers");
    xhttp.send();

What could be a problem?

Phiter
  • 14,570
  • 14
  • 50
  • 84
Azrim
  • 51
  • 6

1 Answers1

0

You should not set those headers in JS, they should be set by the server before it sends the response back to you, if CORS is properly configured.

The Access-Control headers are processed by the browser which will prevent requests from non allowed origins from being run.

Darxtar
  • 2,022
  • 22
  • 21
  • "It's a security to prevent Cross Site Request Forgery attacks." — CSRF is a completely different kind of attack. – Quentin Mar 29 '18 at 12:33
  • "Are you setting those headers clients side?" — Why are you asking that? You can see in code in the question that they are. – Quentin Mar 29 '18 at 12:33
  • From what I understand: Access-Control-Origins will help prevent unauthorised origins to perform requests, so in the case of CSRF, the attacking website will not succeed to perform a POST on someone's behalf. CORS, does not restrict access to data, but instead instructs the browser to specifically allow access to responses from cross-origin requests. While Anti-CSRF tokens should still be used because we shall not rely on client side security, I understand that Access-Control headers help prevent CSRF attacks. – Darxtar Mar 29 '18 at 14:53
  • "Access-Control-Origins will help prevent unauthorised origins to perform requests" — Rarely. Primarily (the lack of it) it stops JavaScript from *reading* the data in the response after it makes the request. – Quentin Mar 29 '18 at 15:49
  • Yes from what I read it would fail for requests needing preflight request but would still reach the server in other cases. The response would not be readable by JS, but that would be enough to do some damage is some cases. – Darxtar Mar 29 '18 at 17:34