Browsers use a security feature to inhibit HTTP calls from one website to another called the "Same Origin Policy." If you want to consume information from an API on your frontend client (meaning your frontend client is making an HTTP request directly to an API), one of 3 things needs to be true:
- The API you're calling to has explicitly enabled CORS (Cross Origin Resource Sharing). This doesn't happen all that often. APIs like the Pokemon API and the Star Wars API have, which is why you've been able to get information from them without problems.
- The API you're calling to has to enable JSONP, and you have to make a JSONP call from your client. JSONP stands for JSON with Padding. The specifics are outside the scope of this post, but just know that it allows you to get info from the API directly.
- You need to write a server to relay requests for you. The server doesn't have the Same Origin Policy restriction that browsers have, so you would make a request to your own server, your server would make the request to the API, the API sends data to your server, and your server sends it back to you.
Since you haven't learned how to write a server yet, we wrote a simple request forwarder for you!
How to use
Make a GET or POST request from your client to the Base URL with a query parameter of
url. Set the value of
url to the URL of the API you want to get info from.
Note: If making a POST request, include your request body like you would normally, and the forwarder will pass it along for you.
Query parameters allow you to provide additional information in the URL of your request. You may have noticed a
? and possibly some
& scattered in your url bar before. For example, when you do a google search for "cors", the URL changes to:
In that URL,
? indicates the beginning of a "query string". Think of them like key-value pairs:
q is the key,
cors is the value. (Separated in the URL by
Say you want to get a random joke from the Chuck Norris Database. According to the docs, the URL to get a random joke is
Using the V School cors api, you would make your request to:
Everything else should work relatively smoothly.
The V School CORS request forwarder is pretty limited right now. It will only work on APIs that don't require authentication of any kind. Maybe in the future we'll add that capability.
You won't want to use this resource forever or for everything. If the API you're accessing allows front-end access, use it! Once you learn how to write your own server, do it that way instead! But in a pinch,
vschool-cors.herokuapp.com is there for you to use on your toy projects. :)
Have fun accessing APIs!