I have been trying to send data to mongoDB using the fetch API along with FormData, but encountering an error:
POST https://xxxxxxxxxxxxxxxxxxxxxxxx/upload 500 (Internal Server Error)
The form data in my EJS file appears as follows:
<div id="image_data">
<form action="/upload" method="post">
<p class="title_content">Enter data about your photo here:</p>
<br>
<input type="hidden" value=<%= username %> name="username" />
<br>
<input id="Base64IMG" type="hidden" value="" name="imgBase64" />
<br>
<label for="city">City: </label>
<input id="city" placeholder="City" name="city" type="text" />
<br />
<label for="date">Captured on: </label>
<input id="date" placeholder="Date" name="date" type="date" />
<br />
<textarea id="textarea" rows ="5" cols="40" placeholder="Describe your image briefly" name="description" ></textarea>
<br>
<input class="sub" type="submit" value="Upload"/>
</form>
</div>
In my Javascript code where I use the fetch API:
function sendData(formData){
fetch('/upload', {
method: 'POST',
body: formData
})
.then(function(response) {
if (response.ok) {
console.log('POST request sent successfully');
console.log(response)
alert("Success")
// Additional processing steps after successful POST request
} else {
console.log('Error sending POST request');
}
})
.catch(function(error) {
console.log('Error sending POST request:', error.message);
});
}
const form = document.querySelector('#image_data > form')
form.addEventListener('submit', function(event) {
event.preventDefault()
const formData = new FormData(form)
if (navigator.onLine) {
sendData(formData)
} else {
.
.
.
}}
And this is my /upload
route:
router.post("/upload", async (req,res) => {
try {
await img.create(req.body)
if(true){
res.status(200).json({message:true})
}else{
res.status(200).json({message:false})
}
} catch (error) {
console.log(error.message);
res.status(500).json({message: error.message})
}
console.log("Upload completed")
})
img
has been imported from a mongoose schema like this:
const img = require("../database/picture");
If anyone can help me pinpoint what I might be doing wrong, it would be greatly appreciated :)
Update: In the server console, I see the following error message:
pictureData validation failed: description: Path `description` is required., date: Path `date` is required., city: Path `city` is required., imgBase64: Path `imgBase64` is required., username: Path `username` is required.
This is my Mongoose Schema:
const mongoose=require("mongoose")
const IMGSchema=new mongoose.Schema({
username:{
type:String,
required:true
},
imgBase64:{
type:String,
required:true
},
city:{
type:String,
required:true
},
date:{
type:String,
type:Date,
required:true
},
description:{
type:String,
required:true
},
})
const img=new mongoose.model("pictureData", IMGSchema)
module.exports=img
´