1

I'm developing a "TODO" app using node.js and mongodb.

I'm trying to post a new task from the client but I didn't success to pass parameters to the server and from there to the database.

Client code:

 <script>
  function addData(item, url) {
    var text = document.getElementById("myTask").value;
     return fetch('/todos',{
      method: 'post',
      body: text
            }).then(response => response.json())
      .then(data => console.log(data));
  }
</script>

Server code:

    app.post('/todos',(req,res) =>{
  console.log("\n\n req.body is:  \n\n",req.body);
  var todo = new Todo({
    text: req.body.text});
    todo.save().then((doc) =>{
      res.send(doc);
      console.log(JSON.stringify(doc,undefined,2));
    },(err) =>{
      res.status(400).send(err); //400 = unable to connect
      console.log("Unable to save todo.\n\n\n" , err);
    });
  });

And the problem is that the client doesn't send the body to the server, and the body is null on the server side: See the logs here (as you can see: req.body = {}) In the js code, I tried to pass the body parameter but I guess I did something wrong so I want to know the best way to pass parameters back to the server (not only the body but text, time and etc)

Thank in advance, Sagiv

Sagiv Asraf
  • 21
  • 1
  • 6

2 Answers2

1

I think that you are missing something. Try to use name of param

body: JSON.stringify({data: text})

OR

read here Fetch: POST json data

Maxim
  • 2,233
  • 6
  • 16
  • I think stringify isn't necessary if you have simple string, but always good practice – Deathmras Dec 27 '18 at 22:48
  • Hi, thanks for your help. I've already tried to solve it by myself and I tried all the solutions on the post you attached. ` function addData() { var textData = { text: document.getElementById("myTask").value }; var data = new FormData(); data.append( "json", JSON.stringify( textData ) ); fetch('/todos', { method: "POST", body: data }) .then(function(res){return res.json();}) .then(function(data){alert( JSON.stringify( data ) ) }) }` I tried this code but still, the request in {} – Sagiv Asraf Dec 29 '18 at 17:06
  • 1
    I succeeded, I had to use async. (this code works for me) : (async () => { const rawResponse = await fetch('https://httpbin.org/post', { method: 'POST', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' }, body: JSON.stringify({a: 1, b: 'Textual content'}) }); const content = await rawResponse.json(); console.log(content); })(); thanks. – Sagiv Asraf Dec 29 '18 at 17:22
  • my congratulations :) – Maxim Dec 29 '18 at 17:24
0

I used this code:

(async () => {
  const rawResponse = await fetch('https://httpbin.org/post', {
    method: 'POST',
    headers: {
      'Accept': 'application/json',
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({a: 1, b: 'Textual content'})
  });
  const content = await rawResponse.json();

  console.log(content);
})();

and now I succeeded to pass data to the request. Thanks everybody

Sagiv Asraf
  • 21
  • 1
  • 6