I’m a computer science student in korea, and I’m working on writing code to post data using react-form-hook, yup, and axios. I need to include JSON inside the form data to send it, but I keep getting a 400 error. Thank you for reading, and I really appreciate any small comments.
"req": {
"username": "string",
"password": "string",
"nickname": "string",
"profileTagIds": [
0
]
},
"profileImage": "string"
}
in swager api,
this is my code
export default function SignUp() {
const {
register,
handleSubmit,
formState: { errors, isValid },
reset,
} = useForm({
resolver: yupResolver(schema),
mode: 'onChange', // onchange 당 체크
});
const onSubmit = async (data) => {
try {
const formData = new FormData();
const file = data.file[0];
const fileAsBase64 = await convertFileToBase64(file);
const json = {
req: {
username: data.email,
password: data.password,
nickname: data.id,
profileTagIds: [0],
},
profileImage: fileAsBase64,
};
const blob = new Blob([JSON.stringify(json)], { type: 'application/json' });
// Append JSON blob with a specific key
formData.append('json', blob);
// formData 내용 출력
Array.from(formData.entries()).forEach(([key, value]) => {
console.log(key, ':', value);
});
const result = await axios.post(`${process.env.REACT_APP_API_URL}/member/join`, formData, {
headers: {
'Content-Type': 'multipart/form-data',
},
});
console.log('success', result.data);
reset();
} catch (error) {
console.error('fail', error.response?.data);
}
};
and this is 400 error :
json :
File {name: 'blob', type:
"application/json"
At first, I was told that I had to use multi-part format data, so I put the image in that format and sent it with json, but the error kept happening. This time, I changed the image to stirng (encoded into base 64) and sent it, but I still get 400 errors.what can i do?
윤여정 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.