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

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

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:

    &lt;div id=&quot;image_data&quot;&gt;        
        &lt;form action=&quot;/upload&quot; method=&quot;post&quot;&gt;
            &lt;p class=&quot;title_content&quot;&gt;Gebe hier Daten &#252;ber dein Foto an:&lt;/p&gt;
            &lt;br&gt;
            &lt;input type=&quot;hidden&quot; value=&lt;%= username %&gt; name=&quot;username&quot; /&gt;
            &lt;br&gt;
            &lt;input id=&quot;Base64IMG&quot; type=&quot;hidden&quot; value=&quot;&quot; name=&quot;imgBase64&quot; /&gt;
            &lt;br&gt;
            &lt;label for=&quot;city&quot;&gt;Ort: &lt;/label&gt;
            &lt;input id=&quot;city&quot; placeholder=&quot;Ort&quot; name=&quot;city&quot; type=&quot;text&quot; /&gt;
            &lt;br /&gt;
            &lt;label for=&quot;date&quot;&gt;Aufgenommen am: &lt;/label&gt;
            &lt;input id=&quot;date&quot; placeholder=&quot;Datum&quot; name=&quot;date&quot; type=&quot;date&quot; /&gt;
            &lt;br /&gt;
            &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;
            &lt;br&gt;
            &lt;input class=&quot;sub&quot; type=&quot;submit&quot; value=&quot;upload&quot;/&gt;
        &lt;/form&gt;
&lt;/div&gt;

my Javascript, where the fetch API is:

function toServer(formData){
   fetch(&#39;/upload&#39;, {
      method: &#39;POST&#39;,
      body: formData
    })
      .then(function(response) {
        if (response.ok) {
          console.log(&#39;POST-Request erfolgreich abgesendet&#39;);
          console.log(response)
          alert(&quot;hat geklappt&quot;)
          // Weitere Verarbeitungsschritte nach erfolgreichem POST-Request
        } else {
          console.log(&#39;Fehler beim Absenden des POST-Requests&#39;);
        }
      })
      .catch(function(error) {
        console.log(&#39;Fehler beim Absenden des POST-Requests:&#39;, error.message);
      });
}

const form = document.querySelector(&#39;#image_data &gt; form&#39;)

form.addEventListener(&#39;submit&#39;, function(event) {
   event.preventDefault()
   const formData = new FormData(form)
   
   if (navigator.onLine) {
      toServer(formData)
    } else {
.
.
.
}}

and my /upload route:

router.post(&quot;/upload&quot;, async (req,res) =&gt; {
  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(&quot;upload wurde durchgef&#252;hrt&quot;)
})

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:

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(&quot;mongoose&quot;)

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(&quot;pictureData&quot;, IMGSchema)

module.exports=img
```&#180;


</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

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:

确定