英文:
How to send data to mongodb with fetch API and FormData
问题
我想使用Fetch API和FormData将数据发送到MongoDB,但我遇到了一个错误:
POST https://xxxxxxxxxxxxxxxxxxxxxxxx/upload 500 (Internal Server Error)
我的EJS文件中的表单数据如下:
<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>
我的JavaScript代码,其中使用了Fetch API:
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 {
// 处理离线情况
// ...
}
})
我的/upload
路由:
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
是从mongoose模式导入的,如下所示:
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: Date,
required: true,
},
description: {
type: String,
required: true,
},
});
const img = new mongoose.model("pictureData", IMGSchema);
module.exports = img;
希望这有助于解决你的问题。如果需要进一步的帮助,请随时提问。
英文:
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
```´
</details>
# 答案1
**得分**: 1
在你的 "pictureData" 模型中,你两次定义了日期字段的类型
```javascript
date:{
type:String,
type:Date,
required:true
}
它应该只被定义一次,就像这样:
date:{
type:Date,
required:true
}
应用这个修改,然后验证应该正常工作。
英文:
In your "pictureData" model, you have defined the type of the date field twice
date:{
type:String,
type:Date,
required:true
}
When it should be defined only once, like this:
date:{
type:Date,
required:true
}
Apply this change, and then the validation should work just fine.
答案2
得分: 0
使用React.js的npm表单模块和类似于final-form的Node模块。
英文:
use a react js npm form module and node module like form final-form
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论