Tip 45: Make Simple AJAX Calls with Fetch
Now, there’s a much simpler tool for AJAX calls:
fetch(). This tip is a little different than the others.
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.
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: