5

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
  • 97,067
  • 19
  • 174
  • 171
Paritosh Mahale
  • 1,018
  • 2
  • 11
  • 35
  • 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

7

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
  • 97,067
  • 19
  • 174
  • 171
  • In node.js (not the browser) you can import `FormData` from the [`form-data` npm module](https://www.npmjs.com/package/form-data). – luckydonald Nov 11 '21 at 00:37
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,303
  • 2
  • 9
  • 30
0

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
  • 7,879
  • 3
  • 27
  • 59