【问题标题】:POST request with Axios not sending data to my serverAxios 的 POST 请求未向我的服务器发送数据
【发布时间】:2020-03-22 13:52:52
【问题描述】:

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

【问题讨论】:

  • 你在节点端使用bodyparser吗?
  • @AmolBJamkar 是的
  • 你确定item变量在前端有值吗?
  • 你在console.log中找到req.body了吗?当您点击发布请求时,您确定 node/express 功能正常吗?
  • 请让一切清楚。 - 您可以检查您的后端是否与 Postman 一起运行良好。 - 如果后端没问题,然后用 Chrome 的 Inspect-> Network 检查你的前端。

标签: node.js reactjs api docker axios


【解决方案1】:

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

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

    • 后端工作正常。我多次测试了端点。但是,数据没有通过 Axios.post 请求发送
    • 你能用我上面提到的代码检查你的反应代码吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-12-12
    • 2021-08-20
    • 1970-01-01
    • 2016-07-03
    • 2021-06-05
    • 2021-06-08
    • 2020-06-05
    相关资源
    最近更新 更多