在客户端使用js添加参数以发布请求

时间:2018-12-27 22:32:24

标签: javascript node.js mongodb post request

我正在使用node.js和mongodb开发一个“ TODO”应用。

我正尝试从客户端发布新任务,但未能成功将参数传递到服务器,再从那里传递到数据库。

客户代码:

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

服务器代码:

    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);
    });
  });

问题是客户端没有将正文发送到服务器, 并且主体在服务器端为null: See the logs here (如您所见:req.body = {}) 在js代码中,我尝试传递body参数,但是我想我做错了,所以我想知道将参数传递回服务器的最佳方法(不仅是body,还包括文本,时间等)

预先感谢, 萨吉夫

2 个答案:

答案 0 :(得分:1)

我认为您缺少什么。尝试使用参数名称

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

OR

在此处阅读Fetch: POST json data

答案 1 :(得分:0)

我使用了以下代码:

(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);
})();

现在我成功将数据传递给请求。 谢谢大家