首页 > 解决方案 > 表单提交值给出 null - mongoose 和 express js

问题描述

我正在尝试使用 express 将数据从基本的 html 表单发送到 mongodb。但是当我发布它时它给了我null。

我使用了以下架构:commentname:String。

这是HTML:

<form id="form" onsubmit="return false;">
  <input type="textbox" id="cmt-1" placeholder="comment here"/>
</form>
<button type="button" onclick="submit()" class="submit">
  submit
</button>

JS:


var cmt = document.getElementById('cmt-1').value;
var comment = {commentname: ''};
comment = {commentname: cmt};

function submit () {
  async function postData (url = '', data = {}) {
    const response = await fetch(url, {
      method: 'POST',
      mode: 'same-origin',
      cache: 'no-cache',
      credentials: 'same-origin',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(data) // body data type must match "Content-Type" header
    });
    return response.json(); // parses JSON response into native JavaScript objects
  }

  postData(
    'https://realtime-comt-system-100.glitch.me/comments/add',{comment}
  )
  .then(data => { console.log(data); });
}

我错过了什么?

标签: javascriptnode.jsexpressmongoosemongoose-schema

解决方案


只需尝试此代码,但请检查我输入的网址。不要放整个 url 只放路径名。也把这段代码复制和粘贴,html和java脚本都把它们都拿走了,因为我改变了它们

var form = document.getElementById('form');


form.addEventListener('submit', async(e) => {
    e.preventDefault();
    
    let cmt = form.cmt.value;
let data = {commentname: cmt};

 const response = await fetch('/comments/add', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(data)
      
      }).then(res =>{
      console.log(res)
      }).catch(err){
      console.error(err)
      }
    
    })
   
<form id="form">
  <input type="textbox" id="cmt-1" name='cmt' placeholder="comment here"/>
</form>
<button type="submit" onclick="submit()" class="submit">
  submit
</button>


推荐阅读