Making Requests Using The JavaScript Fetch API

Craig Stroman
2 min readJan 5, 2021

--

In JavaScript there are many options for making requests to external resources. You can use the built in XMLHttpRequest method. There’s also many libraries you can use such as jQuery and .ajax(), or you can also use Axios.

But in this post I will be talking about the new JavaScript fetch API. Please note this is only supported by newer versions of Chrome, Firefox, Edge, Safari, Opera, and is not supported by Internet Explorer at all. Which is why it might be a good idea to be using Babel with your JavaScript project if you’re not already.

First I’ll go over the most basic example of using fetch, then I will also go over using it with the new async/await way of handling requests.

The most basic way of handling a fetch request is you start of with the fetch() method and pass a URL for the resource in as a option like so:

fetch('https://jsonplaceholder.typicode.com/todos/1')

The next part is the .then method that returns a promise result which is set up the following way:

A shortcut method for retuning JSON from the response would be to add another .then method doing the following:

You can also use fetch to post data. You would do that by adding a configuration object after the URL that includes a method parameter, header parameter, and a body parameter that represents the data being posted. This can be done by the following way:

In this example I’m posting a JSON object that contains the username value to an end point.

Another way of using fetch to get data is with async functions with the await keyword. Most modern browsers support this but like I said before you’re better off using Babel with your project if you’re going to use this.

For this there are 2 main parts. The first part is the async keyword which you place before the function you want to use it in. The second part is using the await keyword which is used within the async function. The await keyword can be used when calling a function that returns a promise such as fetch. You can use it the following way:

If you want to handle errors you can also use the tray catch structure. This would show any errors you get when attempting to fetch your resource. This structure would look like the following:

This will make it so that if for some reason your resource can’t be fetched your JavaScript wont error out with the the try/catch block.

This is the basics of using the JavaScript fetch API for fetching external resources. I used this with the .then method and also the async/await way for handling promises.

You can learn more details about fetch here. You can learn more about the JavaScript async function here.

--

--