8

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?

Tholle
  • 108,070
  • 19
  • 198
  • 189
Paritosh Mahale
  • 1,238
  • 2
  • 14
  • 42
  • 2
    The second argument is supposed to be stringified to JSON and used as the request payload. Is that not what you want? – Tholle Apr 11 '19 at 11:09

3 Answers3

9

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);
  });
};
Tholle
  • 108,070
  • 19
  • 198
  • 189
1

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

var body = new FormData();
body.append('userName', 'test');
body.append('password', 'test');
body.append('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);
    });
Deepak
  • 1,373
  • 2
  • 10
  • 31
-1

What worked for me is to send the form trough params: instead of data:

That way it will be send as GET variables instead of Request Payload and is much easier to read with $_GET in PHP. No idea how to send as post

axios({
    method: 'post',
    params: data,
    url: 'api.php',
  })
  .then((res) => {
    //Perform Success Action
  })
  .catch((error) => {
    // error.response.status Check status code
  }).finally(() => {
    //Perform action in always
  });
Miro
  • 8,402
  • 3
  • 34
  • 72