简体   繁体   English

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

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

Here is my React code for the form submission:这是我用于表单提交的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));
  };

and this is the code in my Node API :这是我的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));
});

When I run the handleSubmit nothing happens.当我运行 handleSubmit 时,什么也没有发生。 I only get the console.logs... Also, here is the error from my server我只得到 console.logs ... 另外,这是我服务器的错误

'ValidationError: item validation failed: name: Path' `name` is required

So it is clear that the data sent over to the api is never received.所以很明显,发送到 api 的数据永远不会被接收到。 I've tried changing it up in many ways I have came across online but no luck.我已经尝试以多种方式更改它,但我在网上遇到过,但没有运气。

I have attached both ways to post data ie Form URL Encoded and JSON. 我已经附上了两种发布数据的方法,即Form URL Encoded和JSON。 For sending Form Url Encoded data we need an additional Library querystring . 为了发送Form Url编码的数据,我们需要一个附加的Library querystring

You can install it using npm install query-string 您可以使用npm install query-string进行npm install query-string

Here is the code for both the requests. 这是两个请求的代码。 You don't need query-string if you are using content type application/json. 如果您使用内容类型application / json,则不需要query-string

Here you go 干得好

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

Use this用这个

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

First of all check whether your backend code is working or not by using postman. 首先,使用邮递员检查您的后端代码是否正常工作。 I think you are getting validation error because of the error of your backend code. 我认为您由于后端代码错误而收到验证错误。 And also check whether that you are implemented the name attribute correctly with its data type. 还要检查您是否正确实现了name属性及其数据类型。 After that update, the react code as below. 更新之后,反应代码如下。

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