Search code examples
javascriptnode.jsexpressmongoosemongoose-schema

Form submit value giving null - mongoose and express js


I am trying to make a way to send data from a basic html form to mongodb using express. but it's giving me null when I post it.

I used the following Schema : commentname: String.

Here's the 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); });
}

What am I missing?


Solution

  • just try this code but check the url i put . don't put the whole url just put the path name . also take this code copy and paste , the html and the java script take them both because i changed both of them

    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>