1

I am trying to send a request to my api deployed in Heroku. I used an XMLHttpRequest object to fire a request to the api. I am trying out a simple GET and no tricks. However, I receive this error:

XMLHttpRequest cannot load https://xxx-xxxx-xx.herokuapp.com/api/foods/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access.

Which is normal for Chrome. However, I wanted to do this the way Postman handles it. How should I make the request to the api so that it allows everything?

I used this Chrome extension and it worked.

https://github.com/vitvad/Access-Control-Allow-Origin/

What I was able to figure out that it is basically setting this rule:

    rule = {
        "name": "Access-Control-Allow-Origin",
        "value": "*"
    };

However, when I try to set it using xhr.setRequestHeader() method, it doesn't work.

<script>
    var xhr = new XMLHttpRequest();
    xhr.open('GET', 'https://xxx-xxxx-xx.herokuapp.com/api/foods/', true);
    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    xhr.onload = function(){
      console.log(xhr)
    }
    xhr.send(null);
</script>
Smoking Sheriff
  • 471
  • 11
  • 23
  • This can only be done globally at the extension level or with a server acting as a proxy. The way to fix this is to have your server app respond with the correct allow headers. – Alex K. Jun 14 '17 at 11:01
  • So, the server has to send Access-Control-Allow-Origin set to *? No way to modify this with XMLHttpRequest or any other way? – Smoking Sheriff Jun 14 '17 at 11:03
  • Not with basic JavaScript, no, that would make the whole concept pointless. Responding correctly will make this issue go away or JSONP may be an option if you are just sending a GET, see [Ways to circumvent the same-origin policy](https://stackoverflow.com/questions/3076414/ways-to-circumvent-the-same-origin-policy). – Alex K. Jun 14 '17 at 11:07
  • Request methods can vary. I need to implement this for all REST methods. However, is it safe to assume that I can specify the list of domains for which I need to allow the header Access-Control-Allow-Origin? – Smoking Sheriff Jun 14 '17 at 11:11

1 Answers1

0

It is your API in Heroku that needs to set the header, not the web client calling it.

Your browser is following the same origin policy by not allowing your page to request a resource in another domain. Your server can use CORS to let the browser know it is ok to make a request from another domain to this particular resource, but this information needs to come from your server.

The extension and Postman are not following the same origin policy like the browser is doing. The browser needs to follow this policy for your security.

How you set those headers really depends on how you implemented your endpoint in Heroku.

Rodrigo5244
  • 5,145
  • 2
  • 25
  • 36