javascript - 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.
解决方案
在较新版本的 .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);
})
}
推荐阅读
- django - 在 Django 中创建用户历史 API
- postgresql - 将 postgres JSON 转换为行
- excel - 如何通过范围内的 ID 和日期过滤找到最大值和最小值
- core-data - Previewing ContentView with CoreData
- multithreading - 优化 OpenCL 缓冲区写入?
- pandas - 递归地列出树/有向图中节点的邻居,对于图中的所有节点,一次一个“级别”?
- here-api - Fleet Telematics Waypoints Sequence response time
- java - 在 Scala 中对 Java 列表进行平面映射
- android - 尝试 UnitTest 时,出现 Jacoco 错误。即使它没有使用
- google-cloud-platform - Terraform:自动进行身份验证以将 GCP 存储桶挂载到 VM