24
loading...
This website collects cookies to deliver better user experience
POST
. In this article, we’ll learn how to use the Axios POST
method both in vanilla JavaScript and in a framework like React.REST
endpoints in browsers and Node.js. Because Axios is a lightweight HTTP client for both Node.js and browsers, it gives users the ability to take advantage of JavaScript’s async await
.POST
, PUT
, PATCH
, GET
, DELETE
, and so on. However, in this article, we will only be looking at the POST
method.POST
method, let’s consider the following scenario:POST
is the Axios method that allows us to do that. Below is what an Axios POST
request looks like:axios.post(url[, data[, config]])
POST
takes three parameters: the url
, data
, and config
.url
is the server path we send the request to; note that it is in string format. The data
then encapsulates the request body that we’re sending or parsing to the url
. This is in object format, which means it has a key and value pair.config
is the third parameter where we specify the header content type, authorization, and so on; this is also in object format.POST
method does, let’s go ahead and see how to use it.fetch()
method. Comparatively, Axios has some advantages over fetch()
..then()
) and with JSON data by default unlike in the Fetch API where we must first convert the request body to a JSON string in the first promise:// With Fetch
fetch(url)
.then((response) => response.json())
.then((data) => console.log(data))
.catch((error) => console.log(error));
// With Axios
axios.get(url)
.then((response) => console.log(response))
.catch((error) => console.log(error));
POST
request, you use the .post()
method, and so on:axios.post() // to perform POST request
axios.get() // to perform GET request
axios.put() // to perform PUT request
axios.delete() // to perform DELETE request
axios.patch // to perform PATCH request
POST
over the Fetch API include the following:fetch()
does not allowPOST
method both in vanilla JavaScript and in React, so we will start with the former and then proceed to the latter.index.html
and index.js
:// index.html
<!DOCTYPE html>
<html>
<head>
<title>Parcel Sandbox</title>
<meta charset="UTF-8" />
</head>
<body>
<div id="app">
<h1>Login Account</h1>
<form action="">
<label for="email">
Email
<input type="email" name="" id="email" />
</label>
<label for="password">
Password
<input type="password" name="" id="password" />
</label>
<button id="btn">Login</button>
</form>
</div>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script src="index.js"></script>
</body>
</html>
index.js
link, we added the Axios CDN.index.js
file that we created and get the email input, password input, and button elements using their Id
s. We can then add an onClick
event listener that triggers the function whenever we click the button:// index.js
const emailInput = document.getElementById("email");
const passwordInput = document.getElementById("password");
const btn = document.getElementById("btn");
btn.addEventListener("click", () => {
const email = emailInput.value;
const password = passwordInput.value;
axios.post("https://reqres.in/api/login", {
email: email,
password: password
})
.then((response) => {
console.log(response);
});
});
[email protected]
and cityslicka
as the email and password values, respectively. If you click the login button, you will get a response token in your console with a 200
status code telling you the POST
request was successful.POST
request we just did in the vanilla JavaScript example in React. To use Axios in React, we must install the Axios package using npm or yarn. In your terminal, install Axios by running either of the following commands:$ npm install axios
$ yarn add axios
App.js
file.handleSubmit
function, let’s call Axios with the POST
method just as we did in the vanilla example:import React, { useState } from "react";
import axios from "axios";
const App = () => {
const [data, setData] = useState({
email: "",
password: ""
});
const handleChange = (e) => {
const value = e.target.value;
setData({
...data,
[e.target.name]: value
});
};
const handleSubmit = (e) => {
e.preventDefault();
const userData = {
email: data.email,
password: data.password
};
axios.post("https://reqres.in/api/login", userData).then((response) => {
console.log(response.status);
console.log(response.data.token);
});
};
return (
<div>
<h1>Login Account</h1>
<form onSubmit={handleSubmit}>
<label htmlFor="email">
Email
<input
type="email"
name="email"
value={data.email}
onChange={handleChange}
/>
</label>
<label htmlFor="password">
Password
<input
type="password"
name="password"
value={data.password}
onChange={handleChange}
/>
</label>
<button type="submit">Login</button>
</form>
</div>
);
};
POST
call. Let’s look at another example where we create a new user or register as a new user:// App.js
import React, { useState } from "react";
import './styles.css';
import axios from "axios";
const App = () => {
const [state, setState] = useState({
name: "",
job: ""
});
const handleChange = (e) => {
const value = e.target.value;
setState({
...state,
[e.target.name]: value
});
};
const handleSubmit = (e) => {
e.preventDefault();
const userData = {
name: state.name,
job: state.job
};
axios.post("https://reqres.in/api/users", userData).then((response) => {
console.log(response.status);
console.log(response.data);
});
};
return (
<div>
<h1>Register or Create new account</h1>
<hr />
<form onSubmit={handleSubmit}>
<label htmlFor="name">
Name
<input
type="text"
name="name"
value={state.name}
onChange={handleChange}
/>
</label>
<label htmlFor="job">
Job
<input
type="text"
name="job"
value={state.job}
onChange={handleChange}
/>
</label>
<button type="submit">Register</button>
</form>
</div>
);
};
styles.css
file and copy the CSS styling below to style the app. It’s nothing fancy, but makes the interface view a bit cooler:// styles.css
body {
padding: 0;
margin: 0;
box-sizing: border-box;
font-family: sans-serif;
}
h1 {
text-align: center;
margin-top: 30px;
margin-bottom: 0px;
}
hr {
margin-bottom: 30px;
width: 25%;
border: 1px solid palevioletred;
background-color: palevioletred;
}
form {
border: 1px solid black;
margin: 0 28%;
padding: 30px 0;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
}
label {
width: 80%;
text-transform: uppercase;
font-size: 16px;
font-weight: bold;
}
input {
display: block;
margin-bottom: 25px;
height: 6vh;
width: 100%;
}
button {
padding: 10px 30px;
text-transform: uppercase;
cursor: pointer;
}
POST
method..catch()
block and allows us to check for certain conditions to see why the error occurs so we can know how to handle them. Let’s see how we can do that below using the first example:const App = () => {
const [data, setData] = useState({
email: "",
password: ""
});
const handleChange = (e) => {
const value = e.target.value;
setData({
...data,
[e.target.name]: value
});
};
const handleSubmit = (e) => {
e.preventDefault();
const userData = {
email: data.email,
password: data.password
};
axios
.post("https://reqres.in/api/login", userData)
.then((response) => {
console.log(response);
})
.catch((error) => {
if (error.response) {
console.log(error.response);
console.log("server responded");
} else if (error.request) {
console.log("network error");
} else {
console.log(error);
}
});
};
return (
<div>
<h1>Login Account</h1>
<form onSubmit={handleSubmit}>
<label htmlFor="email">
Email
<input
type="email"
name="email"
value={data.email}
onChange={handleChange}
/>
</label>
<label htmlFor="password">
Password
<input
type="password"
name="password"
value={data.password}
onChange={handleChange}
/>
</label>
<button type="submit">Login</button>
</form>
</div>
);
};
400
error telling us the user does not exist or there are missing credentials, a 404
error telling us the page was not found, to a 501
error telling us the page is unavailable, and so on.error.toJSON()
to make our error response more readable.GET
requests concurrently using Axios with error handling. Since Axios returns a promise, we can perform multiple GET
requests using Promise.all()
:const getFirstUsers = axios.get("https://reqres.in/api/unknown");
const getSecondUsers = axios.get("https://reqres.in/api/users?page=2");
Promise.all([getFirstUsers, getSecondUsers]).then((response) => {
const firstResponse = response[0];
const secondResponse = response[1];
});
.all()
that works just as Promise.all()
:const firstRequest = axios.get("https://reqres.in/api/unknown");
const secondRequest = axios.get("https://reqres.in/api/users?page=2");
const thirdRequest = axios.get("https://reqres.in/api/users/2");
axios.all([firstRequest, secondRequest, thirdRequest]).then(
axios.spread((...res) => {
const firstRes = res[0];
const secondRes = res[1];
const thirdRes = res[2];
console.log(firstRes, secondRes, thirdRes);
})
)
.catch((error) => {
if (error.response) {
// the request was made and the server responded with a status code
console.log(error.response);
console.log(error.response.status);
} else if (error.request) {
// the request was made but no response was received
console.log("network error");
} else {
// something happened when setting up the request
console.log(error);
}
});
GET
request on any number of APIs of your choice by wrapping it all inside Axios.all()
just like in Promise.all()
. It then calls them as an array and returns a promise. Axios also allows you to spread the response.Promise.all()
and make it more readable:let API = [
"https://reqres.in/api/unknown",
"https://reqres.in/api/users?page=2",
"https://reqres.in/api/users/2"
];
Promise.all(
API.map((api) => {
return axios.get(api).then((res) => {
console.log(res);
});
})
).catch((error) => {
if (error.response) {
// the request was made and the server responded with a status code
console.log(error.response);
console.log(error.response.status);
} else if (error.request) {
// the request was made but no response was received
console.log("network error");
} else {
// something happened when setting up the request
console.log(error.toJSON());
}
});
API
. We then mapped through the API
array and performed the GET
request on each of them.Promise.all
, which means that Promise.all()
waits for all input promises to resolve before returning a promise.POST
requests in vanilla JavaScript and React. We also looked at how Axios allows us to handle our errors better and perform multiple requests using Axios.all
and Promise.all
.Axios.all
as it still works today has been deprecated and it’s advised to use Promise.all
instead. This includes by extension the Axios.spread
.POST
and concurrent GET
requests comfortably. Gracias!