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..
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
yes. I checked with postman and it works perfectly
backend response(console.log(body))
waiting for some help thanks
There's lot of body types like form-data
, x-www-form-urlencoded
..
I found that
form-data
return empty {}
but
x-www-form-urlencoded
return what i expected like { email : "aa@google.com "}
problem was the way receiving formdata in backend(Nest.js)
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?