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?

2 Answers

0
Tholle On Best Solutions

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);
  });
};
0
Deepak rao On

You can do this in axios by using FormData() like

var body = new FormData();
body.set('userName', 'test');
body.set('password', 'test');
body.set('user_type', 1);

And then you can use axios post method (You can amend it accordingly)

axios({
    method: 'post',
    url: 'http://demo.com/api/v1/end-user/login',
    data: body,
    config: { headers: {'Content-Type': 'multipart/form-data' }}
    })
    .then(function (response) {
        //handle success
        console.log(response);
    })
    .catch(function (response) {
        //handle error
        console.log(response);
    });