Axios的POST请求未将数据发送到我的服务器

时间:2019-11-27 04:11:35

标签: node.js reactjs api docker axios

这是我提交表单的反应代码:

  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的数据。我已经尝试过多种在线方式进行修改,但是没有运气。

2 个答案:

答案 0 :(得分:0)

我已经附上了两种发布数据的方法,即表单URL编码和JSON。要发送表单网址编码的数据,我们需要一个附加的库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();

答案 1 :(得分:-1)

首先,使用邮递员检查您的后端代码是否正常工作。我认为您由于后端代码错误而收到验证错误。还要检查您是否正确实现了name属性及其数据类型。 更新之后,反应代码如下。

notificationBuilder.setWhen(System.currentTimeInMillis() - 60_000)