My code isn't working as it should, it keeps receiving a 400 from the server and failing to upload. I must be making mistakes in the react component so please can you take a look for me? All's working in Postman, so the backend code seems fine.
import React, { useState } from "react";
import axios from "axios";
const UploadAvatar = () => {
const [image, setImage] = useState();
const handleUpload = async (e) => {
e.preventDefault();
const config = {
headers: {
"content-type": "multipart/form-data",
Authorization: localStorage.getItem("token"),
},
};
try {
const formData = new FormData();
formData.append("avatar", image);
const response = await axios.post(
"/users/me/avatar",
{ formData },
config
);
console.log(response);
} catch (err) {
console.error(err.message);
}
};
return (
<div>
<form onSubmit={handleUpload}>
Select image to upload:
<input
type="file"
onChange={(e) => setImage(e.target.value)}
name="fileToUpload"
/>
<input type="submit" value="Upload Image" name="submit" />
</form>
</div>
);
};
export default UploadAvatar;
onChangefunction toonChange={(e) => setImage(e.target.files[0])}.