Axios is a popular JavaScript library used to make HTTP requests from a web browser or node.js. Here are the basic steps for using axios:
Install Axios: Before using axios, you need to install it using npm. You can do this by running the following command in your terminal:
Copy code npm install axios Import Axios: Once installed, you need to import axios into your project. You can do this by adding the following line at the top of your file:
const axios = require("axios");
If you are using ES6 or later, you can use the following syntax:
python
import axios from 'axios'; Make an HTTP Request: Now you can use axios to make HTTP requests. Here's an example of making a GET request:
axios
.get("https://jsonplaceholder.typicode.com/posts")
.then((response) => {
console.log(response.data);
})
.catch((error) => {
console.log(error);
});
In this example, we are making a GET request to the JSONPlaceholder API and logging the response to the console. The then method is called when the request is successful, and the catch method is called when there is an error.
Other HTTP Methods: Besides get, axios supports other HTTP methods like post, put, delete, etc. Here's an example of making a POST request:
axios
.post("https://jsonplaceholder.typicode.com/posts", {
title: "foo",
body: "bar",
userId: 1,
})
.then((response) => {
console.log(response.data);
})
.catch((error) => {
console.log(error);
});
In this example, we are making a POST request to create a new post with a title, body, and userId. The data is passed as the second argument to the post method. The response is logged to the console if the request is successful, and the error is logged if there is an error.