【问题标题】:Axios POST to Node TroubleAxios POST 到节点故障
【发布时间】:2020-07-19 20:19:55
【问题描述】:

我正在使用 Axios 将 React 状态数据发布到节点服务器。我的 React 构造函数如下所示:

    constructor(props){
        super(props)
        this.state = {
            formFields: {
                firstName: '',
                lastName: '',
                dateOfBirth: '',
                username: '',
                password: ''
            }
        }
    }

我的提交处理程序:

    submitHandler = (e) => {
        const stateData = this.state;
        console.log(stateData)
        axios({
            method: 'post',
            url: 'http://127.0.0.1:3002/api/posts',
            data: this.state
        })
    }

这是我的 Node/Express 处理程序:

app.post('/api/posts', (req, res) => {
    console.log('got here');
    console.log(req.body);
    res.sendStatus(200)
});

如果我将 Axios 数据更改为状态的单个元素,例如 this.state.formFields.firstName,Node 服务器接收数据并打印到控制台没有问题。但是当我尝试发送整个 this.state 对象时,我无法在节点端记录数据。感谢您的帮助!

【问题讨论】:

    标签: javascript node.js reactjs express axios


    【解决方案1】:

    你可以试试

    submitHandler = (e) => {
            const stateData = this.state;
            console.log(stateData)
            axios({
                method: 'post',
                url: 'http://127.0.0.1:3002/api/posts',
                data: {...this.state}
            })
        }
    

    【讨论】:

      【解决方案2】:

      通过以下帖子解决了这个问题:

      Axios posting empty request

      总而言之,您需要将正确的标头添加到 Axios POST。对提交处理程序的以下更改解决了该问题:

         submitHandler = (e) => {
              axios({
                  method: 'post',
                  url: 'http://127.0.0.1:3002/api/posts',
                  data: this.state,
                  headers: {
                      'Content-Type': 'application/x-www-form-urlencoded'
                  }
              })
          }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2010-11-22
        • 2013-12-30
        • 1970-01-01
        • 2021-05-27
        • 2015-12-05
        • 2013-06-16
        • 1970-01-01
        相关资源
        最近更新 更多