DEV Community

Cover image for How to make Axios POST requests in JavaScript
collegewap
collegewap

Posted on • Originally published at codingdeft.com

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">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      body {
        display: flex;
        justify-content: center;
      }
      .item {
        display: flex;
        justify-content: space-between;
        gap: 20px;
      }
    </style>
  </head>
  <body>
    <form action="" id="login" method="post">
      <h1>Login</h1>
      <p class="item">
        <label for="email"> Email </label>
        <input type="email" name="email" id="email" />
      </p>
      <p class="item">
        <label for="password"> Password </label>
        <input type="password" name="password" id="password" />
      </p>
      <p class="item">
        <input type="submit" value="Login" />
      </p>
    </form>
  </body>
  <script type="text/javascript" src="./index.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
</html>
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
  event.preventDefault()

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

  // Handle validations
  axios
    .post("https://example.con/login", { email, password })
    .then(response => {
      console.log(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)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay