Axios tutorial
Features of axios
make XMLHttpRequest from the browser
make http request from node.js
supports the promise api
intercept the response and request
transform request and response data to json format automatically
cancel request
Csrf attacks protections.
CSRF:
Cross-Site Request Forgery (CSRF) is a type of security vulnerability that occurs when an attacker tricks a user's browser into making an unintended and unauthorized request to a web application on which the user is authenticated. This can lead to actions being performed on behalf of the user without their consent.
Create the instance of axios
const axiosInstance = axios.create({
baseURL: 'https://jsonplaceholder.typicode.com',
timeout: 2000,
headers: {
'Content-Type': 'application/json'
}
});
//now every axios request should be like
axiosInstance.get(config);
Ways to make axios request.
//using the promise for client side.
const res = axios({
method:'get',
url:'relative url'
)}
.then( res => console.log(res.data))// on sucessfull
.catch( err => console.log(err)) //On error
.finally(res => /*do whatever whatever be the response*/)//on everyTime
//using the async await function
//basically for server side
async function getData(){
try{
const res = await axiosInstance({
method: 'get',
url: '/todos/a'
})
console.log(res.data);
}
catch (err) {
console.log(err);
}
};