Home > Enterprise >  axios.post with formData always return empty
axios.post with formData always return empty

Time:11-11

Problems

axios.post with formData always return empty object {}

code of react app

const UserSignup = () => {
  
  const signupUser = async (event) => {
    try {
      event.preventDefault();
      const formData = new FormData(document.getElementById('signupForm'));
      const res = await axios.post(
        `${process.env.REACT_APP_BACKEND}/users/signup`,
        formData
      );

      console.log(res.data);
    } catch (error) {
      console.log(error);
    }
  };

  return (
    <Container>
      <h1>signup form</h1>
      <form onSubmit={signupUser} id="signupForm">
        email : <HTextInput name="email" />
        password :
        <HTextInput name="password" type="password" />
        passwordCheck :
        <HTextInput name="passwordCheck" type="password" />
        <Button type="submit">signup</Button>
      </form>
    </Container>
  );
};

I checked..

  • is formData key-values stored?

yes. I checked key-values by adding some codes like

...
const formData = new FormData(document.getElementById('signupForm'));

      // FormData key
      for (let key of formData.keys()) {
        console.log(key);
      }

      // FormData value
      for (let value of formData.values()) {
        console.log(value);
      }

      const res = await axios.post(
        `${process.env.REACT_APP_BACKEND}/users/signup`,
        formData
      );
...

key-values printed in browser console

  • is backend(Nest.js) working well?

yes. I checked with postman and it works perfectly

postman screenshot

backend response(console.log(body))

waiting for some help thanks

CodePudding user response:

Try adding {headers: { "Content-Type": "multipart/form-data" }} as a third argument to your axios.post() call.

CodePudding user response:

1. Test with postman


There's lot of body types like form-data, x-www-form-urlencoded..

I found that

  • post data with form-data return empty {}

but

  • post data with x-www-form-urlencoded return what i expected like { email : "[email protected] "}

problem was the way receiving formdata in backend(Nest.js)

2. use UseInterceptors


I add code in nest.js like

...

@Post()
  @UseInterceptors(FileInterceptor('file')) // <-- this
createUser(@Body body: any) {
...

it work well i expected whether content-type is default(x-www-form-urlendcoed) or multipart/form-data in React application

I can't exactly explain why this happened and work.

Can someone explain why?

  • Related