I am trying to upload files using multer
or formidable
. The files are uploaded properly and also stored in the public
folder. I used create-react-app to start with React project.
The problem arises when I click on the submit button to upload the data. I used the fetch API for making the POST request. The page reloads after I click on the submit button, and anything I log on the console is refreshed as well. This was also answered here, but I want to know how do I prevent my page from reloading? Should I store my images outside the public
folder?
Here is my handleSubmit()
function that calls when form is submitted:-
const handleSubmit = async (e) => {
e.preventDefault();
let formData = new FormData();
formData.append("poster", document.getElementById('file').files[0]);
let res = await fetch("http://localhost:5000/api/post/exhibition", {
method: "POST",
body: formData
})
const json = await res.json()
console.log(json)
}
EDIT:- Handling onSubmit
<form onSubmit={handleSubmit} encType="multipart/form-data">
....
</form>