【问题标题】:I have a problem with the data format by sending data to backend with Axios.post通过使用 Axios.post 将数据发送到后端,我遇到了数据格式问题
【发布时间】:2021-01-05 14:53:37
【问题描述】:

请帮忙... 如果我将数据作为数据集发送到后端(如下例所示),服务器会毫无问题地接受数据。

axios.post('http://localhost:8080/repair',
        {
            description: 'Descriptiony',
            registrationNo: '8899',
            expire: '2020-12-13',
            startDate: '2020-11-29',
            status: 'Red',
            errorCode: 'e333',
            repairDescription: 'Reparatur',
            spitzName: 'Gumowa Kaczka'
        })
        .then((response) => {
            console.log(response);
        }, (error) => {
            console.log(error);
        });
    }

但是,如果我将数据作为对象“this.props”发送,那么不幸的是,我从服务器收到错误 500。 这是 this.props 的代码

continue = e => {
        e.preventDefault();
        console.log(this.props);

        axios.post('http://localhost:8080/repair', this.props,
        )
            .then((response) => {
                console.log(response);
                console.log(this.props);
            }, (error) => {
                console.log(error.message);
            });
        this.props.nextStep();
    };

我尝试使用 console.log 查看数据,但似乎是正确的。 非常感谢您的帮助。

【问题讨论】:

  • HTTP 500 是内部服务器错误,意思是“服务器遇到了阻止它完成请求的意外情况。”。你为什么要发布你的客户端代码?你应该看看你的后端为什么会遇到错误。

标签: javascript reactjs forms server axios


【解决方案1】:

Post() 的第二个参数,如果是对象,使用JSON.stringify() 自动序列化,请求的content-type 设置为application/json。确保端点 http://localhost:8080/repair 允许在标头中使用此 content-type,因为默认值可能是 text/json

https://masteringjs.io/tutorials/axios/post

【讨论】:

    【解决方案2】:

    你应该添加你的道具名称:

    axios.post('http://localhost:8080/repair', this.props.propsName)
    

    因为 props 对象有几个默认属性,例如 children 等,可能会导致后端出错。

    【讨论】:

    • 确实有帮助。我没有注意到这个扩展。 JSON.stringify 在我的情况下不是必需的。再次感谢您提供如此明确的帮助。
    【解决方案3】:

    非常感谢 Dimitri Bret! (我无法发表评论,这就是我在这里说谢谢的原因)。我完全忘记了 stringify,我已经读过它了。最后,我能够看到我正在发送到服务器的确切内容,并且以这种形式,后端不会接受它。现在我只需要处理价值观的价值。这是我发送的内容:{"values":{"registrationNo":"1212","startDate":"2021-01-05","expire":"2021-01-15","status":"Red" ,"description":"gggg","errorCode":"gggg","re​​pairDescription":"gggg","spitzName":"gggg"}}

    但它应该是: {"registrationNo":"1212","startDate":"2021-01-05","expire":"2021-01-15","status":"Red","description":"gggg"," errorCode":"gggg","re​​pairDescription":"gggg","spitzName":"gggg"}

    【讨论】:

      猜你喜欢
      • 2021-02-21
      • 2013-03-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-21
      • 2020-01-30
      相关资源
      最近更新 更多