Search code snippets, questions, articles...

Send Form Data in axios POST request

When using axios, a Javascript library for making HTTP requests, to make a POST request, you need to set the data that you want to send as the body of the request. To do this, you can use the axios.post() method, which takes two arguments: the URL of the server you want to send the request to, and the data you want to send. In this article, we will look at how to use axios to make a POST request, and how to set the body of the request.
var formData = new FormData();

formData.append('firstname', 'John');
formData.append('lastname', 'Deo');

axios({
    method: "post",
    url: "/url/to/api/",
    data: formData,
    headers: { "Content-Type": "multipart/form-data" },
})
.then(response => {
    console.log(response);
})
.catch(response => {
    console.log(response);
});

The above code example creates a new FormData object, then appends two fields to it (firstname and lastname) with the corresponding values (John and Deo).

It then makes an HTTP POST request to the specified URL (/url/to/api/), with the FormData object as the request body, and sets the Content-Type header to multipart/form-data.

If the request is successful, the response is logged to the console. If the request is unsuccessful, the error response is logged to the console.

To use the axios in your project, install axios first. You can install it using the below command:

npm install axios

You can also write the above code as below:

const formData = new FormData();
const imgFile = document.querySelector('#img_upload');

formData.append("image", imgFile.files[0]);

axios.post("api/url", formData, {
    headers: {
        "Content-Type": "multipart/form-data",
    },
})
.then((response) => {
    console.log(response);
})
.catch((error) => {
    console.log(error);
});

The code is using the FormData API to construct a key/value pair form. The key is "image" and the value is the file chosen by the user.

This is then posted to an API using axios (a promise based HTTP client).

If the post is successful, the response is logged to the console. If there is an error, it is logged instead.

With async/await - send form data

async function addImage() {
    const formData = new FormData();
    const imgFile = document.querySelector('#img_upload');
    formData.append("image", imgFile.files[0]);

    try {
        const response = await axios.post('api/url', formData, {
            headers: {
                "Content-Type": "multipart/form-data",
            },
        });
      console.log(response);
    } catch (error) {
      console.error(error);
    }
}

Above is an example of an asynchronous function using the axios library to make a POST request.

The first line creates a new FormData object, which is used to store the data that will be sent in the request.

The second line stores a reference to the file input element in a variable. The third line appends the file to the FormData object using the name "image".

The fourth line uses the await keyword to wait for the response from the server before executing the rest of the code.

The response is stored in a variable. If there is an error, it will be caught and displayed in the console.

Was this helpful?
0 Comments