- Mock API Calls
- Generate Fake Data from Schema for Testing
- Graceful error handling
HTTP Call Approaches
The library options depend on where you're running your app. Node provides a built-in package called
http, it's a low-level library that provides basic functionality for making HTTP requests. Now,
request is a popular higher-level library that makes it simpler to make these calls in Node. It provides a streamlined API that many prefer.
The main gripe with a plain XMLHttpRequest is you're doing all the heavy lifting yourself, you have to manually check the ready state, use a verbose API to set the request header and attach to the on readyState change and error events to get the job done. As you can see it's a lot of plumbing.
Most people prefer alternatives that offer a cleaner API. For a long while, people have often reached for jQuery to get this job done. jQuery's
$.ajax object has been the workhorse of the web for many years.
Some more full-featured frameworks like Angular include their own HTTP service, so you don't have to make this decision at all if using them out of the box. But assuming your framework doesn't natively handle HTTP, another increasingly popular option is Fetch, which is a standard proposed by the Web Hypertext Application Technology Working Group. Now, Fetch offers a streamlined API that elegantly handles HTTP calls, however, some browsers lack native support, so you'll want to use a polyfill with this option. You can find polyfills for both the regular version of Fetch or the isomorphic version of Fetch which we're going to talk about in a moment, but it's also worth noting that Fetch is currently a streamlined API, so it doesn't offer all the features of raw XML HTTP requests, or the other libraries that extract XML HTTP requests away that we'll talk about in a moment. So for instance, you can't cancel a Fetch at this time, but this limitation is being actively worked, so although Fetch support is currently being added to popular browsers, it's feature set is expected to grow over time. Here's an example of using Fetch, as you can see, you create a request object and pass that to Fetch. And since Fetch uses process to handle results, you provide a success and error handler to the then function.