Skip to content
javascript

How to make Axios POST requests in JavaScript

Sep 3, 2022Abhishek EH2 Min Read
How to make Axios POST requests in JavaScript

In this article, we will see how to build a login form in HTML and post the form data to an API endpoint using axios.

Building a login form

Create a file called index.html with the following code:

index.html
1<!DOCTYPE html>
2<html lang="en">
3 <head>
4 <meta charset="UTF-8" />
5 <meta http-equiv="X-UA-Compatible" content="IE=edge" />
6 <meta name="viewport" content="width=device-width, initial-scale=1.0" />
7 <title>Document</title>
8 <style>
9 body {
10 display: flex;
11 justify-content: center;
12 }
13 .item {
14 display: flex;
15 justify-content: space-between;
16 gap: 20px;
17 }
18 </style>
19 </head>
20 <body>
21 <form action="" id="login" method="post">
22 <h1>Login</h1>
23 <p class="item">
24 <label for="email"> Email </label>
25 <input type="email" name="email" id="email" />
26 </p>
27 <p class="item">
28 <label for="password"> Password </label>
29 <input type="password" name="password" id="password" />
30 </p>
31 <p class="item">
32 <input type="submit" value="Login" />
33 </p>
34 </form>
35 </body>
36 <script type="text/javascript" src="./index.js"></script>
37 <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
38</html>

Here we have created a form with 2 fields: email and password. We also have a submit button. In the end, we have included 2 scripts, the first is index.js, where we will write our JavaScript logic and the second is axios from the CDN.

Making the POST call using Axios

Create a file called index.js with the following code:

index.js
1const loginForm = document.querySelector("#login")
2
3loginForm.addEventListener("submit", function (event) {
4 // Stop the default submit and page load
5 event.preventDefault()
6
7 const email = document.querySelector("#email").value
8 const password = document.querySelector("#password").value
9
10 // Handle validations
11 axios
12 .post("https://example.con/login", { email, password })
13 .then(response => {
14 console.log(response)
15 // Handle response
16 })
17})

In the adove code:

  • We are getting a reference to the form, and adding a submit handler function to it.
  • We are accessing the email and password entered by the user.
  • We are making axios POST call with the email and password in the request body to the endpoint https://example.con/login.

Do follow me on twitter where I post developer insights more often!

Leave a Comment

© 2023 CodingDeft.Com