Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

axios post data as form data instead of as JSON in payload

Tags:

reactjs

axios

I am just trying my first reactJS app.

In that I am using axios.post() method for sending data.

submitHandler = event => {
  event.preventDefault();
  axios
    .post("http://demo.com/api/v1/end-user/login", {
      username: "",
      password: "",
      user_type: 1
    })
    .then(res => {
      console.log(res);
      console.log(res.data);
    });
}

But when I check into my network tab, data which I am sending along with request is seems to be in payload.

enter image description here

I would like to send the data as form data instead. Am I am missing something?

like image 760
Paritosh Mahale Avatar asked Apr 11 '19 11:04

Paritosh Mahale


People also ask

Does Axios POST send JSON?

The POST request is used to send data to an endpoint. For example, if we have a registration page where users submit their information, this information can be sent as JSON to the endpoint we specify using a POST JSON request.

How do you POST form data with Axios in react?

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", }, }) .

Does Axios automatically convert to JSON?

Axios automatically converts the data to JSON, so you don't have to: // axios const url = 'https://jsonplaceholder.typicode.com/posts' const data = { a: 10, b: 20, }; axios . post(url, data, { headers: { Accept: "application/json", "Content-Type": "application/json;charset=UTF-8", }, }) . then(({data}) => { console.

How send form data in Axios put request?

Sending a PUT Request with Axios The simplest way to make the PUT call is to simply use the put() function of the axios instance, and supply the body of that request in the form of a JavaScript object: const res = await axios. put('/api/article/123', { title: 'Making PUT Requests with Axios', status: 'published' });


1 Answers

If you want to send the data as form data instead of as JSON in the payload, you can create a FormData object and use that as second argument instead.

submitHandler = event => {
  event.preventDefault();

  const formData = new FormData();
  formData.append("username", "");
  formData.append("password", "");
  formData.append("user_type", 1);

  axios.post("http://demo.com/api/v1/end-user/login", formData).then(res => {
    console.log(res);
    console.log(res.data);
  });
};
like image 132
Tholle Avatar answered Sep 28 '22 13:09

Tholle