DEV Community

Cover image for How to make Axios POST requests in JavaScript

Posted on • Originally published at

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:

<!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
      body {
        display: flex;
        justify-content: center;
      .item {
        display: flex;
        justify-content: space-between;
        gap: 20px;
    <form action="" id="login" method="post">
      <p class="item">
        <label for="email"> Email </label>
        <input type="email" name="email" id="email" />
      <p class="item">
        <label for="password"> Password </label>
        <input type="password" name="password" id="password" />
      <p class="item">
        <input type="submit" value="Login" />
  <script type="text/javascript" src="./index.js"></script>
  <script src=""></script>
Enter fullscreen mode Exit fullscreen mode

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:

const loginForm = document.querySelector("#login")

loginForm.addEventListener("submit", function (event) {
  // Stop the default submit and page load

  const email = document.querySelector("#email").value
  const password = document.querySelector("#password").value

  // Handle validations
    .post("https://example.con/login", { email, password })
    .then(response => {
      // Handle response
Enter fullscreen mode Exit fullscreen mode

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.

Top comments (0)