Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
105 views
in Technique[技术] by (71.8m points)

javascript - 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?

question from:https://stackoverflow.com/questions/65861732/form-submit-value-giving-null-mongoose-and-express-js

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...