call an api in javascript

To call an API in JavaScript, you can use several methods, including fetch(), XMLHttpRequest, and third-party libraries like Axios.

Here's an example of calling an API using fetch():

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

This sends a GET request to the specified API endpoint, retrieves the response as JSON, and logs it to the console. If an error occurs, it will also be logged to the console.

Here's an example of calling an API using XMLHttpRequest:

index.tsx
const xhr = new XMLHttpRequest();

xhr.open('GET', 'https://exampleapi.com/api/data');
xhr.responseType = 'json';
xhr.onload = function() {
  console.log(xhr.response);
};
xhr.onerror = function() {
  console.error('Error calling API');
};
xhr.send();
252 chars
12 lines

This sends a GET request to the specified API endpoint, retrieves the response as JSON, and logs it to the console. If an error occurs, it will also be logged to the console.

And finally, here's an example of calling an API using the Axios library:

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

This uses the Axios library to send a GET request to the specified API endpoint, retrieves the response as JSON, and logs it to the console. If an error occurs, it will also be logged to the console.

gistlibby LogSnag