Home > References > Web Development > Reactjs references

How to post form data with axios

Last updated : June 16, 2022

This article explains how to submit a form using axios. In other words, how to make a post request axios. I will use a simple React app to post form data to a simple express back end.

1. Install axios in your React project

If you haven't installed axios yet, you can run the below command to install axios.
npm i axios or yarn add axios
That will add the axios dependency to your project's package.json file.
"axios": "^0.27.2"

2. Submitting a form using axios

You only need axios dependency installed to use axios. This code shows how to submit a simple form using axios.

import axios from 'axios';
import { useState } from 'react';

export const App = () => {
  interface person {
    name: string
    website: string
    email: string
  }
  interface response {
    response: string | "No Response"
  }
  let initialState: person = {
    name: "LearnBestCoding",
    website: "www.learnbestcoding.com",
    email: "abc@learnbestcoding.com"
  }
    const inputStyle = {border: "1px solid black", height: 75, "padding": 10}
    const [person, setPerson] = useState<person>(initialState)
    const [response, setResponse] = useState<response>()

    const sumbitForm = (e: React.FormEvent<HTMLFormElement>) => {
      e.preventDefault()
      axios.post<response>('http://localhost:8082/user/create', person)
      .then((response) => {
        setResponse(response.data)
        console.log(response.data)
      })
      .catch(function (error) {
        console.log(error);
      });
    }
    const onChangeHandler = (event: HTMLInputElement) => {
      const {name, value} = event
        setPerson((prev) => {
          return {...prev, [name]: value}
        })
    }
     return(
          <form onSubmit={sumbitForm}>
            <table style={inputStyle}>
              <tbody>
                <tr><td>Name:</td><td><input type="text" name="name" value={person.name} onChange={(e) => onChangeHandler(e.target)}/></td></tr>
                <tr><td>Age:</td><td><input type="text" name="age" value={person.website} onChange={(e) => onChangeHandler(e.target)}/></td></tr>
                <tr><td>Email:</td><td><input type="text" name="email" value={person.email} onChange={(e) => onChangeHandler(e.target)}/></td></tr>
                <tr><td ><button type="submit">Submit</button></td></tr>
                {response?.response && <tr><td colSpan={2}>{response.response}</td></tr>}
              </tbody>
            </table>
          </form>
     )
   }
export default App;

3. Submitting forms with images or files

If your axios post includes files, axios accepts an object with header properies. That allows you to customize your post request.

axios({
     method: "post",
     url: "http://localhost:8082/user/create",
     data: person,
     headers: { "Content-Type": "multipart/form-data" },
   })
   .then((response) => {
     setResponse(response.data)
     console.log(response.data)
   })
   .catch(function (error) {
     console.log(error);
});

4. Creating a simple express api

We posted the form in the above steps. The api destination is http://localhost:8082/user/create. Now let's create a simple express server to handle the post request.

4.1 Install express server

Create a folder to host the server. I will name it express. In a terminal, go to the express folder and run the below commands to install express.

npm init
npm install express --save

4.2 Install nodemon

nodemon is a filesystem watcher. It allows hot deploy your node application after any file system changes.
npm install --save-dev nodemon
Add the starter scrips to package.json

"start": "node index.js",
"dev": "nodemon index.js"

Hot deployment takes effect when you start the server as npm run dev.

4.3 Install cors

This dependency is to allow cross-origin resource sharing. By default, your browser blocks any api calls accross different domains.
npm install cors

4.4 Creating the server

Create index.js in the express folder.

const express = require('express');
const app = express();
const cors = require('cors');
const port = 8082

app.use(express.json());
app.use(cors());

app.listen(port, () => {
    console.log(`Server running on port: ${port}`);
});

const router = express.Router();
router.post("/user/create", (request, response) => {
    const {name, website, email} = request.body;
    const reply = `Welcome ${name}, You website is ${website}. We will send you an email to ${email}`
    response.json({response:reply});
});
app.use(router);

4.5 Start the express server

Run npm run dev to start the server in development mode. For production mode, run npm start. For production environments, you should use something like process manager pm2. Now your Ractjs app is ready to send requests to the express back end.

L Raney
By: L Raney
Lance is a software engineer with over 15 years of experience in full-stack software development.
Read more...

Comments are disabled

No Comments