繁体   English   中英

使用 Axios 的 POST 请求不向我的服务器发送数据

[英]POST request with Axios not sending data to my server

这是我用于表单提交的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 的数据永远不会被接收到。 我已经尝试以多种方式更改它,但我在网上遇到过,但没有运气。

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

您可以使用npm install query-string进行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();

用这个

const qs = require('querystring'); qs.stringify(data)

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

import axios from 'axios';


constructor() {
  this.item = {
    name: ''
  }
}

 handleSubmit(event) {
    console.log('item:', this.item.name);
    event.preventDefault();

    axios.post('http://<MY_SERVER>/item/add', this.item)
    .then(response => {
        console.log(response.data);
    })
    .catch(error => {
        console.log(error);
    });

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM