Categories
JavaScript Answers

How to make a JSON call to an URL with JavaScript?

Spread the love

Sometimes, we want to make a JSON call to an URL with JavaScript.

In this article, we’ll look at how to make a JSON call to an URL with JavaScript.

How to make a JSON call to an URL with JavaScript?

To make a JSON call to an URL with JavaScript, we use fetch.

For instance, we write

const getJSON = async (url) => {
  const response = await fetch(url);
  return response.json();
};

const data = await getJSON("https://yesno.wtf/api");
console.log(data);

to define the getJSON function.

In it, we call fetch with url to make a get request to url.

Then we get the response from the returned promise with await.

We get the JSON response body by calling json.

Then we call getJSON and get the response body with await.

Conclusion

To make a JSON call to an URL with JavaScript, we use fetch.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *