ollog10
ollog10

Reputation: 111

GET Requests with Superagent Access-Control-Allow-Origin error

I am using superagent (installed with npm) to get information from an api. Here's the code in a javascript file:

    const http = require('superagent');

http
.get('https://random.dog/woof.json')
.end( function(err, res) {
    console.log(err);
    console.log(res.body);
});

I can test this in my terminal by typing node app.js. Two messages appear in the console, first null, then { url: 'https://random.dog/2d394360-33e1-4c27-9e64-d65a2ab82d5b.jpg' }, which is what I am looking for. I then use a browserify command (browserify app.js -o bundle.js) to make my javascript file usable in an html file. Here is my html file's code:

    <html>
    <head>

    </head>
    <body>
        <h1>Text</h1>
        <script src="bundle.js"></script>
    </body>
    </html>

Relatively simple. This was just to make sure everything was smooth. I opened the HTML file in my browser (the latest version of firefox) and opened the developer console.This error appeared. I was mildly annoyed. I had used this exact same API when I was coding a discord bot and had experienced no issues. So, naturally I changed browsers. Same error. I did some research and still was a bit confused, so I tried to set a header. New js file:

const http = require('superagent');

http
.get('https://random.dog/woof.json')
.set('Access-Control-Allow-Origin', '*')
.end( function(err, res) {
    console.log(err);
    console.log(res.body);
});

This time, this error appeared. It seemed to be along the same lines. Fortunately, I own a little website, so I uploaded these html and js files to the server. I had the exact same error. I even changed the .set('Access-Control-Allow-Origin', '*') to .set('Access-Control-Allow-Origin', 'http://example.com') (with example.com being the domain of my website, of course). There was no difference. I decided to see if I could just make the request using the javascript in the html file, without calling in any other sources. I tried this code:

var HttpClient = function() {
            this.get = function(aUrl, aCallback) {
                var anHttpRequest = new XMLHttpRequest();
                anHttpRequest.onreadystatechange = function() { 
                    if (anHttpRequest.readyState == 4 && anHttpRequest.status == 200)
                        aCallback(anHttpRequest.responseText);
                }

                anHttpRequest.open( "GET", aUrl, true );            
                anHttpRequest.send( null );
            }
        }
        var client = new HttpClient();
        client.get('http://random.dog/woof.json', function(response) {
            console.log(response);
        });

and opened the new html file in firefox. I had the same error as the first time.

Why am I receiving these errors? What can I do to fix these errors? Thanks in advance.

Upvotes: 0

Views: 8754

Answers (1)

skirtle
skirtle

Reputation: 29112

An Ajax request to a different domain is blocked by default by the same-origin policy. The only way to allow such an Ajax request is via CORS, which requires the server to have CORS enabled.

https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS https://www.html5rocks.com/en/tutorials/cors/

It is the server that must have the Access-Control-Allow-Origin header, not the client. As an example, try calling out to https://api.github.com/ rather than https://random.dog/woof.json, you'll find that you can access that URL because it has the CORS headers enabled.

Historically JSON-P was also used as a workaround for the same-origin policy but it is generally inferior to CORS and also requires server support.

A third way to solve this problem would be to reverse proxy the remote server through the server you use for your site so that the origins match. This approach can work well in some circumstances but brings it's own scaling and security considerations.

Upvotes: 1

Related Questions