Tip 45: Make Simple AJAX Calls with Fetch
In this tip, you’ll learn how to retrieve remote data using fetch().
We'll cover the following
AJAX calls
If you do any significant JavaScript app development, you’ll have to interact with APIs. With APIs, you can get current information and update single elements without a page refresh. In short, you can create very fast applications that behave like native software.
Single-page web apps are part of the reason why JavaScript is so popular, but getting data with AJAX—Asynchronous JavaScript And XML—used to be a hassle. It was such a hassle that most developers used a library, usually jQuery, to to reduce the complexity. You can see the documentation on the Mozilla Developer Network. It’s not easy stuff.
Using fetch()
Now, there’s a much simpler tool for AJAX calls: fetch()
. This tip is a little different than the others. fetch()
isn’t part of the JavaScript spec. The fetch
spec is defined by the Web Hypertext Application Technology Working Group or
WHATWG. That means you’ll be able to find it in most major browsers, but
it isn’t natively supported in Node.js. If you want to use it in Node.js, you’ll
need to use the node-fetch package.
Enough trivia. How does it work?
To start, you need an endpoint. The good folks at typicode have an API for fake blog data. They also make an amazing tool called JSON Server that enables you to mock APIs locally. JSON Server is a great way to mock APIs that are in development or slow, require authentication, or cost money for each call. You should use it.
Now that you have an endpoint, it’s time to make some requests.
GET requests
The first request you’ll make is a simple GET request. If all you’re doing is
asking for data, the fetch()
call is simple. Call fetch()
with the endpoint URL as the argument:
Get hands-on with 1400+ tech skills courses.