How to Send Form Data Using Axios Post Request In React

How to Send Form Data Using Axios Post Request In React

React is the leading programming language used by developers globally. More than 8,787 industry leaders were using React.js in 2020. Hence, multiple developers prefer to go for React and Javascript. Multiple encoding types can be used for non-file transfers.

Form data:

One of the encoding types allows the files to be incorporated into the required form data before being transferred to the server for processing. Some other encoding types used for the non-file transfers include text/ plain, application/x-www-form-urlencoded, etc. Moreover, Bosc Tech has a skilled developers who have developed various react application using React. Hire skilled React developers from BOSC Tech Labs for your next project, and they will assist you in the proper implementation of Send Form Data Using Axios Post Request in your React-based projects.

While multipart or form-data allows the files to be included in the form data, text/ plain sends the data as plain text without encoding. It is used for debugging and not for production. The application/x-www-form-urlencoded encodes the data as query string – separating key – value pairs assigned with “ = “ and other symbols like “&.”

All these encoding types can be added to the HTML using the “enctype” attribute in the following way:

These encoding types are used with HTML “<form>” tag. The default setting works well with the different cases; this attribute is often missing.

Axios

Axios is a widely-used promise-based HTTP client for making XMLHttpRequests in browsers and HTTP requests in Node.js environments. It seamlessly integrates with the “Promise” API and offers features such as request/response interception, request/response data transformation, automatic JSON data handling, and built-in client-side protection against Cross-Site Request Forgery (XSRF) attacks.

While Axios originally relied on native ES6 Promise implementations, it’s worth noting that most modern environments now offer native Promise support. For older environments lacking ES6 Promise support, Axios can be polyfilled for compatibility.

Although Axios was initially inspired by AngularJS’s “$http service,” it has evolved into a versatile HTTP client library suitable for use in various JavaScript frameworks and environments.

Browser Support:

Axios is compatible with a wide range of browsers, including Edge, Internet Explorer, Opera, Safari, Mozilla Firefox, and Google Chrome.

For updated information and best practices on using Axios, consider referring to the official documentation and community resources.

Additionally, explore our article on modern techniques for managing input field state after rendering in React applications.

Also, check out our article on 4 ways to Set Input Field After Rendering in React.

Common request methods:

Axios provides a convenient API for performing various HTTP request methods:

  • axios.get(url[, config])
  • axios.post(url[, data[, config]])
  • axios.put(url[, data[, config]])
  • axios.patch(url[, data[, config]])
  • axios.delete(url[, config])
  • axios.options(url[, config])
  • axios.head(url[, config])
  • axios.request(config)

These methods offer flexibility and ease of use when interacting with RESTful APIs or backend services.

Common instance methods:

Some of the available instance methods in Axios are:

  • axios#getUri([config])
  • axios#patch(url[, data[, config]])
  • axios#put(url[, data[, config]])
  • axios#post(url[, data[, config]])
  • axios#options(url[, config])
  • axios#head(url[, config])
  • axios#request(config)
  • axios#delete(url[, config])
  • axios#get(url[, config])

1. Installing Axios:

Axios is commonly used to send HTTP requests over the “fetch()” command. For different Node projects, it is easy to install Axios using “npm.”

npm install axios
or
yard add axios

The other way to install Axios is to include it in CDN directly or download the files to the system. The library in markup is included like:

2. Setting “enctype” with HTML and Axios:

It is important to set the encoding type to send the multipart data or files through form data. It is easy to set the default global encoding type with Axios, which enforces all Axios requests in multipart/ form – data encoding type in the following way:

axios.defaults.headers.post['Content-Type'] = 'multipart/form-data';

The encoding type can be defined for separate individual requests by altering the “headers” in the following way:

axios.post(“api/path”, formData, {
	headers: {
	“Content-type”: “multipart/form-date”,
},
});

The third way to set the encoding type is to set the “enctype” in the “<form>” of a specific form. Axios adopts the following encoding type in the following way:

<form action="/api-endpoint" method="POST" enctype="multipart/form-data">

3. Axios and Express:

Let us consider the case where a simple form with two inputs is created in Axios and Express. One is used for the user to submit their name, and the other one is used to select the profile image in the following way:

Name :

Select a file :

If Axios is not used in the program, the default set of events unfolds. Pressing the “Submit” button will send a “POST” request to the “/update – profile” endpoint of our server. This default behaviour can be overridden by attaching an event listener to the button and preventing the unfolding of the default events.

A simple example of attaching the event listener, preventing the default behaviour, and sending our form data using Axios is mentioned below. It is easy to customize the request before sending it out and altering the headers as all Axios requests are entailed synchronically.

 
const form = document.querySelector("form");
  if (form) {
    form.addEventListener("submit", (e) => {
      e.preventDefault();
      const formData = new FormData(form);
      axios
        .post("/update-profile", formData, {
          headers: {
            "Content-Type": "multipart/form-data",
          },
        })
        .then((res) => {
          console.log(res);
        })
        .catch((err) => {
          console.log(err);
        });
    });

The request is forwarded to the “http: / / localhost : 5000 / update – profile” endpoint with dedicated upload support files when the form is filled and the “Submit” button is clicked. It all comes down to the endpoint, which receives and processes the request.

Schedule an interview with React developers

4. Express Backend:

The REST API is spun using Express.js for the backend support. Hence, developers can focus on development than on the different setups. This technique sets the server and handles requests. Express is expandable with middleware and works on minimalist coding. It becomes easy to expand the core functionality of Express by installing simple or complex middleware.

Express can be installed using “npm.” The “express – fileupload” middleware can be used for simple file handling with Express. The simple technique for the same is:

npm install express express-fileupload

Let us start a server and define the endpoint that accepts the “POST” to “/update – profile.”

const express = require("express");
var fileupload = require("express-fileupload");
const app = express();
app.use(fileupload());
app.use(express.static("public"));
app.use(express.urlencoded({ extended: true }));
app.post("/update-profile", (req, res) => {
  let username = req.body.username;
  let userPicture = req.files.userPicture;
  console.log(userPicture);
  res.send(`
    Your username is: ${username}
    Uploaded image file name is ${userPicture.name}
  `);
});

app.listen(3001, () => {
  console.log("Server started on port 3001");
});

The “req” request passed through the request handler carries data sent by the form. The body contains all data from the different set fields like the “username.” All the files created are located in the “req” object under the “files” field. Further, it is easy to access the input “username” through “req . body . username.” The uploaded files can be accessed using “req . files . userPicture.”

The following response is received in the browser console when the form is submitted with the HTML page:

Sample Form
Sample Form

If information like encoding type, file name, and other information is required, it is easy to log the “req. files .userPicture” to the console.

Wrapping Up:

Hence, it is easy to understand the Axios post request to send form data. Axios is the leading asynchronous HTTP library that is used to send post requests carrying the file or multipart data. The REST API is used to handle the request. It accepts the incoming file and other form data using the “enctype” attribute. This attribute is set with Axios.


Book your appointment now

Get in touch





    Stay up-to-date with our blogs