Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript AJAX Basics (retiring) AJAX and APIs Making the AJAX Request

John Bastian Bolhano
John Bastian Bolhano
4,800 Points

How do we do this in pure JavaScript?

I want to try this whole section with pure JS. Here is my code.

const flickrRequest = new XMLHttpRequest;
    const url = 'https://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?';

    flickrRequest.onreadystatechange = function () {
      if (this.readState === 4 && this.status === 200) {
        console.log(flickrRequest.responseText);
      }
      else {
        console.log(this.status);
      }
    }

    flickrRequest.open('GET', url);
    flickrRequest.send();

It spits out an error:

port-80-m8ubrkwqov.treehouse-app.com/:1 Failed to load https://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://port-80-m8ubrkwqov.treehouse-app.com' is therefore not allowed access.

Is there a way to fix this or do we just have to stick with jQuery?

1 Answer

Steven Parker
Steven Parker
231,236 Points

Flickr does not support CORS headers on api.flickr.com, so fetch and XMLHttpRequest will not work.

jQuery is sending a JSONP request and evaluating the JavaScript served in Flickr's response with an injected <script> element.

It's ugly, but you can get around this by making the request through a CORS proxy server.