首页 > 解决方案 > Axios createError.js:16 Uncaught (in promise) 错误:请求失败,状态码 400

问题描述

新的反应在这里。我收到了这个错误:xhr.js:177 POST https://localhost:44355/api/people/addperson 400我不知道为什么。我检查了整个 StackOverflow,但找不到类似问题的好答案。

在我的页面上,我有 3 个文本框(名字、姓氏、年龄)和一个添加按钮,用于将人员添加到文本框下方的表格中。单击添加按钮时发生错误。

这是我的控制器:

public class PeopleController : ControllerBase
    {
        private string _connectionString;

        public PeopleController(IConfiguration configuration)
        {
            _connectionString = configuration.GetConnectionString("ConStr");
        }

        [HttpPost]
        [Route("addperson")]
        public void AddPerson(Person person)
        {
            var repo = new PeopleRepository(_connectionString);
            repo.AddPerson(person);
        }
    }

这是我的组件:

import React from 'react';
import AddEditPerson from './AddEditPerson';
import PersonRow from './PersonRow';
import axios from 'axios';
import { produce } from 'immer';

class PeopleTable extends React.Component {
    state = {
        people: [],
        person: {
            firstName: '',
            lastName: '',
            age :''
        },
        isAdd : true
    }

    componentDidMount = () => {
        axios.get('/api/people/getpeople').then(response => {
            this.setState({ people: response.data })
        })
    }

    onAddClick = () => {
        axios.post('/api/people/addperson', this.state.person).then(() => {
            axios.get('/api/people/getpeople').then(response => {
                const person = {
                    firstName: '',
                    lastName: '',
                    age:''
                }
                this.setState({ people: response.data, person})
            })
        })
    }
}
//here I have a render function that shows a component with the textboxes 
//and the onClick for the add button is the onAddClick function above.

标签: javascriptreactjsaxios

解决方案


在较新版本的 .Net 中,他们更改了 json 在服务器上的解析方式。过去,如果你有一个这样的 json:{prop: "100"} 并且在服务器上你有一个这样的类:

public class Foo
{
   public int Prop {get; set;}
}

它将能够将 json 转换为该 C# 对象 - (请注意,在 json 道具中是一个字符串,而在 c# 中它是一个 int)。

在 .Net Core 3.1 中,他们更改了此功能,json 将不再正确解析。因此,这this.state.person.age是一个字符串,但在 C#Age中是一个整数,最好创建一个新对象,解析年龄,并将其发送到函数中。

我更新了我的代码:

onAddClick = () => {
        const { firstName, lastName, age } = this.state.person;
        const person = { firstName, lastName, age: parseInt(age) }
        axios.post('/api/people/addperson', person).then(response => {
            const newState = produce(this.state, draft => {
                const person = {
                    firstName: '',
                    lastName: '',
                    age: ''
                }
                draft.person = person;
                draft.people.push(response.data);
            })

            this.setState(newState);            
        })
    }

感谢@BFree@Zied Hf


推荐阅读