0

I am trying to make a request to ping my backend api with XMLHttpRequest.

Following is my code

var r = new XMLHttpRequest();
r.open("POST", 'domain:port/path/');
r.setRequestHeader("Access-Control-Allow-Origin", '*');
r.setRequestHeader("Accept", 'application/json ');

var data = {"key":"value"};

r.send(data);

But I always accept the following error message

Access to XMLHttpRequest at 'domain:port/path/' from origin 'http://localhost:8000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Firstly; I think that's because I didn't set "Access-Control-Allow-Origin". But even I set it, it's not working.

How can I solve my problem?

Thanks.

ZarNi
  • 3
  • 1
  • Possible duplicate of [No 'Access-Control-Allow-Origin' header is present on the requested resource—when trying to get data from a REST API](https://stackoverflow.com/questions/43871637/no-access-control-allow-origin-header-is-present-on-the-requested-resource-whe) – Eydrian Jan 11 '19 at 06:16

2 Answers2

1

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

it is a response header, you need to set Access-Control-Allow-Origin on your server-side code

Srikanth_K
  • 11
  • 2
0

Access-Control-Allow-Origin is a response header, not a request header. Your server decides what origins are allowed to access it. If it were that easy to bypass, would it really be a security measure? :-) If what you truly want is for that endpoint to allow any domain to access it, then you have to add the header, there.

Leroy Stav
  • 722
  • 4
  • 12