Axios is a Javascript library used to make HTTP requests from your frontend to your backend API.
Axios is easier and more convenient than built-in fetch API.
Method Purpose
axios.get() Fetch data
axios.post() Create/submit data
axios.put() Update entire resource
axios.patch() Partial update
axios.delete() Delete data
How to use Axios in Your Projects
Step1: Install Axios
step2: Basic Axios Usage
Here are the common HTTP methods:
`import axios from ‘axios’
import axios from ‘axios’
// GET request
axios.get(‘http://localhost:3000/api/users’)
.then(response => console.log(response.data))
.catch(error => console.log(error))
// POST request
axios.post(‘http://localhost:3000/api/users‘, {
name: ‘John’,
email: ‘john@example.com‘
})
.then(response => console.log(response.data))
.catch(error => console.log(error))
// PUT request (update)
axios.put(‘http://localhost:3000/api/users/1‘, {
name: ‘Jane’
})
.then(response => console.log(response.data))
.catch(error => console.log(error))
// DELETE request
axios.delete(‘http://localhost:3000/api/users/1′)
.then(response => console.log(response.data))
.catch(error => console.log(error))
_Step 3: In React components (with hooks)_
import React, { useState, useEffect } from ‘react’
import axios from ‘axios’
function UserList() {
const [users, setUsers] = useState([])
const [loading, setLoading] = useState(false)
const [error, setError] = useState(null)
// Fetch data on component mount
useEffect(() => {
fetchUsers()
}, [])
const fetchUsers = async () => {
setLoading(true)
try {
const response = await axios.get(‘http://localhost:3000/api/users’)
setUsers(response.data.users)
setError(null)
} catch (err) {
setError(err.message)
} finally {
setLoading(false)
}
}
if (loading) return
Loading…
if (error) return
Error: {error}
return (
{users.map(user => (
{user.name}
{user.email}
))}
)
}
export default UserList
axios.post(‘http://localhost:3000/api/auth/login‘,
_Step 4: With authentication (sending tokens)_
{email,password},
{
withCredentials:true, // Send cookies
headers:{
‘Content-Type’:’application/json’
}
}
)`
Step 5: Create a reusable Axios instance
create src/api/axiosInstance.js:
import axios from 'axios'
const axiosInstance = axios.create({
baseURL:'http://localhost:3000/api',
withCredentials:true
})
// Add token to all requests
axiosInstance.interceptors.request.use(config => {
const token = localStorage.getItem('token')
if (token) {
config.headers.Authorization = `Bearer ${token}`
}
return config
})
export default axiosInstance
Then use it in components:
import axiosInstance from '../api/axiosInstance'
//Instead of full URL
axiosInstance.post('/auth/login',{email,password})
.then(response => console.log(response.data))