如何使用fetch API和FormData将数据发送到MongoDB。

huangapple go评论110阅读模式
英文:

How to send data to mongodb with fetch API and FormData

问题

我想使用Fetch API和FormData将数据发送到MongoDB,但我遇到了一个错误:

POST https://xxxxxxxxxxxxxxxxxxxxxxxx/upload 500 (Internal Server Error)

我的EJS文件中的表单数据如下:

  1. <div id="image_data">
  2. <form action="/upload" method="post">
  3. <p class="title_content">Gebe hier Daten über dein Foto an:</p>
  4. <br>
  5. <input type="hidden" value=<%= username %> name="username" />
  6. <br>
  7. <input id="Base64IMG" type="hidden" value="" name="imgBase64" />
  8. <br>
  9. <label for="city">Ort: </label>
  10. <input id="city" placeholder="Ort" name="city" type="text" />
  11. <br />
  12. <label for="date">Aufgenommen am: </label>
  13. <input id="date" placeholder="Datum" name="date" type="date" />
  14. <br />
  15. <textarea id="textarea" rows="5" cols="40" placeholder="Beschreibe kurz dein Bild" name="description"></textarea>
  16. <br>
  17. <input class="sub" type="submit" value="upload"/>
  18. </form>
  19. </div>

我的JavaScript代码,其中使用了Fetch API:

  1. function toServer(formData){
  2. fetch('/upload', {
  3. method: 'POST',
  4. body: formData
  5. })
  6. .then(function(response) {
  7. if (response.ok) {
  8. console.log('POST-Request erfolgreich abgesendet');
  9. console.log(response)
  10. alert("hat geklappt")
  11. // Weitere Verarbeitungsschritte nach erfolgreichem POST-Request
  12. } else {
  13. console.log('Fehler beim Absenden des POST-Requests');
  14. }
  15. })
  16. .catch(function(error) {
  17. console.log('Fehler beim Absenden des POST-Requests:', error.message);
  18. });
  19. }
  20. const form = document.querySelector('#image_data > form')
  21. form.addEventListener('submit', function(event) {
  22. event.preventDefault()
  23. const formData = new FormData(form)
  24. if (navigator.onLine) {
  25. toServer(formData)
  26. } else {
  27. // 处理离线情况
  28. // ...
  29. }
  30. })

我的/upload路由:

  1. router.post("/upload", async (req, res) => {
  2. try {
  3. await img.create(req.body);
  4. if (true) {
  5. res.status(200).json({ message: true });
  6. } else {
  7. res.status(200).json({ message: false });
  8. }
  9. } catch (error) {
  10. console.log(error.message);
  11. res.status(500).json({ message: error.message });
  12. }
  13. console.log("upload wurde durchgeführt");
  14. })

img 是从mongoose模式导入的,如下所示:

  1. const mongoose = require("mongoose");
  2. const IMGSchema = new mongoose.Schema({
  3. username: {
  4. type: String,
  5. required: true,
  6. },
  7. imgBase64: {
  8. type: String,
  9. required: true,
  10. },
  11. city: {
  12. type: String,
  13. required: true,
  14. },
  15. date: {
  16. type: Date,
  17. required: true,
  18. },
  19. description: {
  20. type: String,
  21. required: true,
  22. },
  23. });
  24. const img = new mongoose.model("pictureData", IMGSchema);
  25. 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:

  1. &lt;div id=&quot;image_data&quot;&gt;
  2. &lt;form action=&quot;/upload&quot; method=&quot;post&quot;&gt;
  3. &lt;p class=&quot;title_content&quot;&gt;Gebe hier Daten &#252;ber dein Foto an:&lt;/p&gt;
  4. &lt;br&gt;
  5. &lt;input type=&quot;hidden&quot; value=&lt;%= username %&gt; name=&quot;username&quot; /&gt;
  6. &lt;br&gt;
  7. &lt;input id=&quot;Base64IMG&quot; type=&quot;hidden&quot; value=&quot;&quot; name=&quot;imgBase64&quot; /&gt;
  8. &lt;br&gt;
  9. &lt;label for=&quot;city&quot;&gt;Ort: &lt;/label&gt;
  10. &lt;input id=&quot;city&quot; placeholder=&quot;Ort&quot; name=&quot;city&quot; type=&quot;text&quot; /&gt;
  11. &lt;br /&gt;
  12. &lt;label for=&quot;date&quot;&gt;Aufgenommen am: &lt;/label&gt;
  13. &lt;input id=&quot;date&quot; placeholder=&quot;Datum&quot; name=&quot;date&quot; type=&quot;date&quot; /&gt;
  14. &lt;br /&gt;
  15. &lt;textarea id=&quot;textarea&quot; rows =&quot;5&quot; cols=&quot;40&quot; placeholder=&quot;Beschreibe kurz dein Bild&quot; name=&quot;description&quot; &gt;&lt;/textarea&gt;
  16. &lt;br&gt;
  17. &lt;input class=&quot;sub&quot; type=&quot;submit&quot; value=&quot;upload&quot;/&gt;
  18. &lt;/form&gt;
  19. &lt;/div&gt;

my Javascript, where the fetch API is:

  1. function toServer(formData){
  2. fetch(&#39;/upload&#39;, {
  3. method: &#39;POST&#39;,
  4. body: formData
  5. })
  6. .then(function(response) {
  7. if (response.ok) {
  8. console.log(&#39;POST-Request erfolgreich abgesendet&#39;);
  9. console.log(response)
  10. alert(&quot;hat geklappt&quot;)
  11. // Weitere Verarbeitungsschritte nach erfolgreichem POST-Request
  12. } else {
  13. console.log(&#39;Fehler beim Absenden des POST-Requests&#39;);
  14. }
  15. })
  16. .catch(function(error) {
  17. console.log(&#39;Fehler beim Absenden des POST-Requests:&#39;, error.message);
  18. });
  19. }
  20. const form = document.querySelector(&#39;#image_data &gt; form&#39;)
  21. form.addEventListener(&#39;submit&#39;, function(event) {
  22. event.preventDefault()
  23. const formData = new FormData(form)
  24. if (navigator.onLine) {
  25. toServer(formData)
  26. } else {
  27. .
  28. .
  29. .
  30. }}

and my /upload route:

  1. router.post(&quot;/upload&quot;, async (req,res) =&gt; {
  2. try {
  3. await img.create(req.body)
  4. if(true){
  5. res.status(200).json({message:true})
  6. }else{
  7. res.status(200).json({message:false})
  8. }
  9. } catch (error) {
  10. console.log(error.message);
  11. res.status(500).json({message: error.message})
  12. }
  13. console.log(&quot;upload wurde durchgef&#252;hrt&quot;)
  14. })

img is importet from a mongoose schema from const img = require(&quot;../database/picture&quot;);

Can somebody help me, what im doing wrong. 如何使用fetch API和FormData将数据发送到MongoDB。

EDIT:
in the console of my server i get this output:

  1. 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:

  1. const mongoose=require(&quot;mongoose&quot;)
  2. const IMGSchema=new mongoose.Schema({
  3. username:{
  4. type:String,
  5. required:true
  6. },
  7. imgBase64:{
  8. type:String,
  9. required:true
  10. },
  11. city:{
  12. type:String,
  13. required:true
  14. },
  15. date:{
  16. type:String,
  17. type:Date,
  18. required:true
  19. },
  20. description:{
  21. type:String,
  22. required:true
  23. },
  24. })
  25. const img=new mongoose.model(&quot;pictureData&quot;, IMGSchema)
  26. module.exports=img
  27. ```&#180;
  28. </details>
  29. # 答案1
  30. **得分**: 1
  31. 在你的 "pictureData" 模型中,你两次定义了日期字段的类型
  32. ```javascript
  33. date:{
  34. type:String,
  35. type:Date,
  36. required:true
  37. }

它应该只被定义一次,就像这样:

  1. date:{
  2. type:Date,
  3. required:true
  4. }

应用这个修改,然后验证应该正常工作。

英文:

In your "pictureData" model, you have defined the type of the date field twice

  1. date:{
  2. type:String,
  3. type:Date,
  4. required:true
  5. }

When it should be defined only once, like this:

  1. date:{
  2. type:Date,
  3. required:true
  4. }

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

huangapple
  • 本文由 发表于 2023年7月7日 04:10:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/76632250.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定