calling api in javascript

To call an API in JavaScript, there are several methods available, including Fetch, Axios, and jQuery's Ajax method.

Here is an example using the Fetch API:

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

This code sends a GET request to the specified URL, gets the response, and converts it to JSON. Then, it logs the JSON data to the console. If there is an error, it logs the error to the console.

Here is an example using Axios:

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

This code sends a GET request to the specified URL using Axios, gets the response, and logs the response data to the console. If there is an error, it logs the error to the console.

Here is an example using jQuery's Ajax method:

index.tsx
$.ajax({
  url: 'https://api.example.com/data',
  method: 'GET',
  dataType: 'json',
  success: data => console.log(data),
  error: error => console.error(error)
});
166 chars
8 lines

This code sends a GET request to the specified URL using jQuery's Ajax method, gets the response, and logs the JSON data to the console. If there is an error, it logs the error to the console.

related categories

gistlibby LogSnag