create an api request using axios in javascript

Here's an example of how to create an API request using axios in JavaScript:

index.tsx
import axios from 'axios';

// Make a request for a user with a given ID
axios.get('https://jsonplaceholder.typicode.com/posts/1')
  .then(function (response) {
    // handle success
    console.log(response.data);
  })
  .catch(function (error) {
    // handle error
    console.log(error);
  });

// Alternatively, we can send data in the request body
axios.post('https://jsonplaceholder.typicode.com/posts', {
    title: 'foo',
    body: 'bar',
    userId: 1
  })
  .then(function (response) {
    console.log(response.data);
  })
  .catch(function (error) {
    console.log(error);
  });
592 chars
26 lines

In this example, we are using axios to make a GET request to the JSONPlaceholder API to retrieve a post with an ID of 1. We also have an example of making a POST request with data in the request body. The response data is logged to the console in both cases, and any errors are caught and logged as well.

gistlibby LogSnag