CORS support using search api

I’m quite new as JS, APIs, CORS, etc. I’m attempting to use the twitch search api in codepen, pen here, and I keep getting “Not Found” error. I’m using a callback function in the url to handle CORS (from what I’ve researched that should handle it) but to no resolution. If I paste the url to my browser address bar I get “Bad Request” but without the “callback=?” I do get the JSON I expect. Furthermore, I am able to get non-search api results that I expect using callback=? in the url (which seems to support that CORS is being handled).

Search api url example: https://api.twitch.tv/kraken/search/streams?q=world_of_warcraft&callback=? (doesn’t work in codepen with or without the callback=? ending, works in browser without.)

Other api url example: https://api.twitch.tv/kraken/streams/freecodecamp?callback=? (works in codepen with the callback=? ending, works in browser without.)

Does the search api not support JSON-P? Is codepen to blame (doesn’t seem to be as non-search api calls work), or is my code wrong (I’m noob, can’t help but assume this). Any help is much appreciated. Thanks!

EDIT: The portion of this code in question may be edited out so I can continue with the basic part of the Free Code Camp project. The search component is not required, just something I would like to figure out.

Hey, @jmcgloin!

JSON-P is supported on all endpoints including search. There are three problems in your code:

  1. You’re not passing the URL to $.getJSON. So, the request is going out to nowhere, which is why you’re getting Not Found. I figured this out by using the DevTools in Chrome (specifically, the network tab) to see that the response was returning a CodePen 404.
  2. Only the first query string parameter has a question mark (?) in front of it. The rest are appended using an ampersand (&). You’re currently using a question mark (?) for all of your arguments.
  3. The data being returned isn’t an array but a JSON object. You need to get the _total property of the object rather than trying to index into an array that doesn’t exist.

If you fix those three things, it’ll all work just fine. :slight_smile: I have the working code for this, but I’m going to leave it up to you to fix for the sake of learning!

Let me know if you have more questions!

Thanks very much! With your help I have solved my problem. I also appreciate your pointing out how you found my problem. That will help me in the future for sure.

No problem at all! Debugging is a critical skill that isn’t often taught or even mentioned when people are learning, so I figured it was good to call out here. :slight_smile: When I taught JavaScript courses, I always taught the fundamentals of debugging using Chrome or Firefox. It’ll save you lots of time as you learn!

1 Like

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.