Get , Post, Put, Delete in Axios
Source: Dev.to
Installation
npm
npm install axios
bower
bower install axios
yarn
yarn add axios
Importing Axios
import axios from 'axios';
Fundamentals of Axios
GET Request
axios.get('url')
.then((response) => {
// handle success
console.log(response);
})
.catch((error) => {
// handle error
console.log(error);
});
POST Request
axios.post('url', {
id: 1,
name: 'rohith'
})
.then((response) => {
// handle success
console.log(response);
})
.catch((error) => {
// handle error
console.log(error);
});
PUT Request
axios.put('url', {
id: 1,
name: 'ndrohith'
})
.then((response) => {
// handle success
console.log(response);
})
.catch((error) => {
// handle error
console.log(error);
});
DELETE Request
axios.delete('url', {
id: 1,
})
.then((response) => {
// handle success
console.log(response);
})
.catch((error) => {
// handle error
console.log(error);
});
Using Axios in a React Class
import React, { Component } from "react";
import axios from "axios";
class AxiosRequests extends Component {
constructor(props) {
super(props);
this.state = {};
}
async componentDidMount() {
try {
await axios({
url: url,
method: "GET",
}).then((res) => {
// handle success
console.log(res);
});
} catch (e) {
// handle error
console.error(e);
}
}
postData = async (e) => {
e.preventDefault();
const data = { id: 1, name: "rohith" };
try {
await axios({
url: url,
method: "POST",
data,
}).then((res) => {
// handle success
console.log(res);
});
} catch (e) {
console.error(e);
}
};
putData = async (e) => {
e.preventDefault();
const data = { id: 1, name: "ndrohith" };
try {
await axios({
url: url,
method: "PUT",
data,
}).then((res) => {
// handle success
console.log(res);
});
} catch (e) {
console.error(e);
}
};
deleteData = async (e) => {
e.preventDefault();
const data = { id: 1 };
try {
await axios({
url: url,
method: "DELETE",
data,
}).then((res) => {
// handle success
console.log(res);
});
} catch (e) {
console.error(e);
}
};
render() {
return <>;
}
}
export default AxiosRequests;
Note:
async/awaitis an ECMAScript 2017 feature not supported by Internet Explorer and older browsers; use it with caution.
Reference: Axios Documentation