db.json
The image file I posted to my db.json is missing.
const createPost = async (title, image, description) => {
const data = new FormData();
data.append('title', title);
data.append('image', image);
data.append('description', description);
const response = await axios.post('http://localhost:3001/posts', data, {
headers: {
'Content-Type': 'application/json',
},
});
const updatedPosts = [...posts, response.data];
setPosts(updatedPosts);
};
export const Form = ({ createPost }) => {
const [image, setImage] = useState(null);
const submitForm = (e) => {
e.preventDefault();
createPost(title, image, description);
setImage('');
setTitle('');
setDescription('');
};
const uploadImage = (e) => {
const file = e.target.files[0];
setImage(file);
};
return (
<form onSubmit={submitForm} encType="multipart/form-data">
<div className="image">
<label>Import Image</label>
<input type="file" accept="image/*" onChange={(e) => uploadImage(e)} />
</div>
<div className="action">
<Button className="button">Create</Button>
</div>
</form>
);
};
I want to post my data to my server. But, only an image file is missing in my db.json. What is the better way I fixed the code?
3
Answers
I think your header’s content type have to be multipart/form-data or you have to convert your image to base64 string and no need to add it to form data and also if you are using express you may have to use bodyparserand fs packages too.
onChange
takes only function name. So, modify thisto
because you have already defined
uploadImage
function earlier in your code.I don’t know, but I think your problem is in the Backend code. But, try to Change the order of
data.append
, movedata.append(file)
to the last.If not work, please show me your backend code. (how to generate db.json file)