Axios Module make HTTP requests from your Node.js server or script, like fetching or sending data to APIs.
Install axios Module
npm install axios
Exmple:
// Fetch Data
const axios = require('axios');
let apiUrl = 'http://localhost:3000/api/users';
axios.get(apiUrl)
.then(response => {
const users = response.data;
console.log('User data:', users[2].name);
})
.catch(error => {
console.error('Error fetching data:', error.message);
});
apiUrl = 'http://localhost:3000/api/users';
axios.post(apiUrl, {
name: 'rose donaldo',
email: '[email protected]'
})
.then(response => {
console.log('Post Created:', response.data);
})
.catch(error => {
console.error('Error:', error.message);
});
//PUT Request
apiUrl = 'http://localhost:3000/api/users/2';
axios.put(apiUrl, {
name: 'john roy'
})
.then(response => {
console.log('Updated Post:', response.data);
});
//DELETE Request
apiUrl = 'http://localhost:3000/api/users/2';
axios.delete(apiUrl)
.then(response => {
console.log('Deleted:', response.data);
});
Comments