这是我的对表单提交的React 代码:

  const handleSubmit = (e) => {
    e.preventDefault();
    console.log('item:', item);
    Axios.post('http://<MY_SERVER>/item/add', {name:item})
      .then(response => console.log(response))
      .catch(err => console.log(err));
  };

这是我的 Node API 中的代码:
// Add a new Item
app.post('/item/add', (req, res) => {
  const newItem = new Item({
    name: req.body.name
  });

  newItem.save()
    .then(item => {
    res.json({msg: 'success'});
    })
    .catch(err => console.log(err));
});

当我运行handleSubmit时,没有任何反应。我只得到console.logs ...而且,这是我服务器的错误
'ValidationError: item validation failed: name: Path' `name` is required

因此很明显,永远不会接收发送到api的数据。我已经尝试过多种在线方式进行修改,但是没有运气。

最佳答案

我已经附上了两种发布数据的方法,即表单URL编码和JSON。为了发送Form Url编码的数据,我们需要一个附加的Library querystring

您可以使用npm install query-string安装它

这是两个请求的代码。如果使用内容类型application / json,则不需要query-string

干得好

var axios = require('axios');
const qs = require('querystring');

function sendFormUrlEncodedData() {
  const headers = {
    'Content-Type': 'application/x-www-form-urlencoded'
  };

  const payload = {
    name: 'morpheus',
    job: 'leader'
  };

  //Send data with form url using querystring node package for it.
  axios
    .post('https://reqres.in/api/users', qs.stringify(payload), {
      headers: headers
    })
    .then(res => {
      console.log(res.data);
    })
    .catch(err => {
      console.log(err);
    });
}

function sendJSONData() {
  const headers = {
    'Content-Type': 'application/json'
  };

  const payload = {
    name: 'morpheus',
    job: 'leader'
  };

  //Send data with JSON, so stringifying it.
  axios
    .post('https://reqres.in/api/users', JSON.stringify(payload), {
      headers: headers
    })
    .then(res => {
      console.log(res.data);
    })
    .catch(err => {
      console.log(err);
    });
}

sendFormUrlEncodedData();
sendJSONData();

09-26 19:53
查看更多