Open In App
Related Articles

How to post a file from a form with Axios?

Improve Article
Improve
Save Article
Save
Like Article
Like

In this article, we are going to discuss making POST requests with form data using the Axios library. Axios is a Promise based HTTP client that can be used for the web as well as for Node.JS development. However, in this article, we are going to strictly refer to client-side use of Axios.

To start off, we need to add axios to our development by using a CDN link :

<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"> </script>

In order to use extract data from our form, we are going to use the FormData() method. The formdata method converts the data input in the form in the form of key-value pairs to create a multipart/form-data object.

HTML:




<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" 
        content="width=device-width, 
                 initial-scale=1.0">
  <script src=
          crossorigin="anonymous">
  </script>
  <title>Document</title>
</head>
  <body>
  <h3 style="color:green; font-size:25px;">
    Geeks For Geeks
  </h3>
  <form>
    <input name="first-name"/><br>
    <input name="last-name"/><br>
    <input name="address"/><br>
    <button type="submit">Submit</button>
  </form>
</body>
</html>


Output:

Axios Post Request Syntax
There are two ways to make an axios post request :

  1. Standard post request:

    axios.post(url, data).then(callbackFn()).catch(callbackFn(err))
    url : The request url for HTTP POST.
    data : An object containing the POST data
    callbackFn() : Callback functions to handle the promise.

  2. Post Request with a configuration object


  3. axios({
    method : ‘post’,
    url : url,
    data : data
    headers : headers
    }).then(callbackFn()).catch(callbackFn())

    method : specifies the HTTP method
    data : an object containing the POST data.
    headers(optional) : An object to specify the headers associated with the request.

Javascript Code to send form data to servers :




window.addEventListener('load', ()=>{
        
       const form = document.querySelector('form');
       form.addEventListener('submit', (e)=>{
           //to prevent reload
           e.preventDefault();
           //creates a multipart/form-data object
           let data = new FormData(form);
           axios({
             method  : 'post',
             url : '/',
             data : data,
           })
           .then((res)=>{
             console.log(res);
           })
           .catch((err) => {throw err});
       });
   });


Testing the Axios request with a mock rest API:
Front End Code:




<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta name="viewport"
              content="width=device-width, 
                       initial-scale=1.0" />
        <script src=
                integrity=
"sha512-VZ6m0F78+yo3sbu48gElK4irv2dzPoep8oo9LEjxviigcnnnNvnTOJRSrIhuFk68FMLOpiNz+T77nNY89rnWDg==" 
                crossorigin="anonymous"></script>
        <title>Document</title>
    </head>
    <body>
        <h3 style="color: green; font-size: 25px;">
            Geeks For Geeks
        </h3>
        <form>
            <input name="first-name" /><br />
            <input name="last-name" /><br />
            <input name="address" /><br />
            <button type="submit">Submit</button>
        </form>
  
        <script type="text/javascript">
            window.addEventListener("load", () => {
                const form = document.querySelector("form");
                form.addEventListener("submit", (e) => {
                    e.preventDefault();
                    let data = new FormData(form);
                    console.log(data);
                    axios({
                        method: "post",
                        url: "/",
                        data: data,
                    })
                        .then((res) => {
                            console.log(res);
                        })
                        .catch((err) => {
                            throw err;
                        });
                });
            });
        </script>
    </body>
</html>


Code for the Node.js based mock REST API:




const express = require('express');
const formidable = require('express-formidable');
  
const app = express();
  
app.use(express.static(__dirname+'/index.html'));
app.use(formidable());
  
app.get('/', (req, res)=>{
    res.sendFile(__dirname+'/index.html');
});
  
app.post('/', (req, res)=>{
      
    console.log(JSON.stringify(req.fields));
});
  
app.listen('3000', ()=>{
    console.log('listening to port');
  
});


Sample Request Data:

Output in console:

{"first-name":"Geeks", "last-name":"Geeks", "address":"Noida"}

Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Last Updated : 10 Sep, 2020
Like Article
Save Article
Previous
Next
Similar Reads
Complete Tutorials