How to post a file from a form with Axios? - GeeksforGeeks

10 Sep, 2020
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="https://cdnjs.cloudflare.com/ajax/libs/axios/0.19.2/axios.min.js"           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 SyntaxThere are two ways to make an axios post request :
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 datacallbackFn() : Callback functions to handle the promise.Post Request with a configuration objectaxios({method : ‘post’,url : url,data : dataheaders : headers}).then(callbackFn()).catch(callbackFn())method : specifies the HTTP methoddata : an object containing the POST data.headers(optional) : An object to specify the headers associated with the request.
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 datacallbackFn() : Callback functions to handle the promise.Post Request with a configuration object
axios.post(url, data).then(callbackFn()).catch(callbackFn(err))url : The request url for HTTP POST.data : An object containing the POST datacallbackFn() : Callback functions to handle the promise.
Post Request with a configuration object
axios({method : ‘post’,url : url,data : dataheaders : headers}).then(callbackFn()).catch(callbackFn())method : specifies the HTTP methoddata : an object containing the POST data.headers(optional) : An object to specify the headers associated with the request.
method : specifies the HTTP methoddata : 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="https://cdnjs.cloudflare.com/ajax/libs/axios/0.19.2/axios.min.js"                 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"}
JavaScript-Misc
Picked
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between var, let and const keywords in JavaScript
How to create a link in JavaScript ?
How to Show Images on Click using HTML ?
Remove elements from a JavaScript Array
How to remove an HTML element using JavaScript ?
Express.js express.Router() Function
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
Difference between var, let and const keywords in JavaScript