简体   繁体   中英

axios.post with formData always return empty

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

尝试添加{headers: { "Content-Type": "multipart/form-data" }}作为axios.post()调用的第三个参数。

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 : "aa@google.com "}

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM