request api in javascript

There are several ways to request an API in JavaScript. One of the commonly used methods is using the fetch() API, which is built into modern browsers. The fetch() method is used to make a request to a server and retrieve a response.

Here's an example of how to use the fetch() method to make an API request:

index.tsx
fetch('https://api.example.com/data')
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error(error));
151 chars
5 lines

Another method to make an API request is by using the XMLHttpRequest object. This method is older and not as frequently used as fetch(), but it is still supported by all browsers.

Here's an example of how to use XMLHttpRequest to make an API request:

index.tsx
let xhr = new XMLHttpRequest();
xhr.open('GET', 'https://api.example.com/data');
xhr.onload = function() {
  if (xhr.status === 200) {
    console.log(xhr.responseText);
  } else {
    console.error('Error!');
  }
};
xhr.send();
229 chars
11 lines

There's also another popular library called axios which can be used to make API calls. It's a lightweight library and supports promises by default.

Here's an example of how to use axios to make an API request:

index.tsx
axios.get('https://api.example.com/data')
  .then(response => console.log(response.data))
  .catch(error => console.error(error));
131 chars
4 lines

gistlibby LogSnag