I want to send data to mongoDB with the fetch API and FormData, but i get an error:
POST https://xxxxxxxxxxxxxxxxxxxxxxxx/upload 500 (Internal Server Error)
My form data in EJS file is this:
<div id="image_data">
<form action="/upload" method="post">
<p class="title_content">Gebe hier Daten über dein Foto an:</p>
<br>
<input type="hidden" value=<%= username %> name="username" />
<br>
<input id="Base64IMG" type="hidden" value="" name="imgBase64" />
<br>
<label for="city">Ort: </label>
<input id="city" placeholder="Ort" name="city" type="text" />
<br />
<label for="date">Aufgenommen am: </label>
<input id="date" placeholder="Datum" name="date" type="date" />
<br />
<textarea id="textarea" rows ="5" cols="40" placeholder="Beschreibe kurz dein Bild" name="description" ></textarea>
<br>
<input class="sub" type="submit" value="upload"/>
</form>
</div>
my Javascript, where the fetch API is:
function toServer(formData){
fetch('/upload', {
method: 'POST',
body: formData
})
.then(function(response) {
if (response.ok) {
console.log('POST-Request erfolgreich abgesendet');
console.log(response)
alert("hat geklappt")
// Weitere Verarbeitungsschritte nach erfolgreichem POST-Request
} else {
console.log('Fehler beim Absenden des POST-Requests');
}
})
.catch(function(error) {
console.log('Fehler beim Absenden des POST-Requests:', error.message);
});
}
const form = document.querySelector('#image_data > form')
form.addEventListener('submit', function(event) {
event.preventDefault()
const formData = new FormData(form)
if (navigator.onLine) {
toServer(formData)
} else {
.
.
.
}}
and 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 wurde durchgeführt")
})
img
is importet from a mongoose schema from const img = require("../database/picture");
Can somebody help me, what im doing wrong. 🙂
EDIT:
in the console of my server i get this output:
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.
My mongoose Scheema is this:
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
```´
2
Answers
In your "pictureData" model, you have defined the type of the date field twice
When it should be defined only once, like this:
Apply this change, and then the validation should work just fine.
use a react js npm form module and node module like form final-form