请求中的req正文中的空对象

时间:2018-03-09 20:32:45

标签: node.js express

我无法从req.body获取正确的数据

当我向服务器提取请求时,我会在我的控制台中获取此信息(例如:'洗碗'作为输入的值)

// console log
{}
{ item: 'Wash dishes' }

首先是空对象,然后是我指定的项目。

html文件

<form autocomplete="off" id="formform" method="POST">
            <input type="text" name="item" placeholder="Add new item..." required id="inputinput" >
            <button type="submit">Add Item</button>
</form>

测试-W-fetch.js

let newForm = document.getElementById('formform');

newForm.addEventListener('submit', (evt) =>{
  let item = document.getElementById('inputinput');
  let todo = {item: item.value};


  fetch('/todo', {
    method: 'POST',
    headers: {
      'Accept': 'application/json',
      'Content-Type': 'application/json'
    },
    body: todo
  }).then( (response) => {
    return response.json();
  }).then((data) =>{

      location.reload();
  }).catch((err) =>{
    console.log(`There's an ${err}!!`);
  });

  return false;
}); 

这是我在服务器上的POST路线

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

app.post('/todo', (req, res) => {
    // Need to get data from the view and add it to mongodb
    console.log(req.body);

    let newItem = new Todo(req.body);

    newItem.save( (err, data) =>{
        if (err) throw err;

        res.json(data);
    }); 
});

我尝试过的其他选项是对错误检查req.body.item属性,将其存储到新对象中,并将其传递给数据库,但空对象仍然通过正文并保存到数据库< / p>

1 个答案:

答案 0 :(得分:0)

您可以尝试的一件事是使用Postman来查看问题是服务器端还是客户端。有助于缩小故障排除表面区域。

相关问题