4

New to react here. I'm getting this error: xhr.js:177 POST https://localhost:44355/api/people/addperson 400 and I can't figure out why. I checked all over StackOverflow, but couldn't find a good answer from similar questions.

On my page, I have 3 textboxes (first name, last name, age) and an ADD button to add a person to a table beneath the textboxes. The error occurs when I click the add button.

Here's my controller:

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

Here's my component:

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.
5
  • 1
    Since it's 400 this is a bad request. Are you sure this is not a CORS problem ? Check your console maybe there is an error related to CORS. Or maybe your server expect to receive specific header ? And are you able to use the same API on Postman ? (The good practice for POST request is to return the new added value, then you don't have to use a get request after each post) Commented Jan 7, 2021 at 0:05
  • You axios requests don't have a .catch block. You need to add one and print out the error to see what's happening - since it's a 400 there's likely an issue with the data you're sending, either missing values or the wrong shape or something Commented Jan 7, 2021 at 0:05
  • @Jayce444 I added a catch to log the error in the console, and here's what I got: Error: Request failed with status code 400 at createError (createError.js:16) at settle (settle.js:17) at XMLHttpRequest.handleLoad (xhr.js:62) Commented Jan 7, 2021 at 1:09
  • @mamaj instead of logging the error, try to log the "response" property of it, e.g. console.log(error.response). Also if you can edit backend code, you could add logging on the backend to try and see what the issue is Commented Jan 7, 2021 at 4:18
  • are you sure https://localhost:44355 is not you're front localhost port ? Commented Jan 9, 2021 at 8:33

1 Answer 1

1

In newer versions of .Net they made a change to how the json gets parsed on the server. It used to be that if you had a json like this: {prop: "100"} and on the server you had a class like this:

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

it would be able to convert the json to that C# object - (notice that in the json prop is a string and in c# it’s an int).

In .Net Core 3.1 they changed this feature, and the json would no longer parse correctly. Therefore, being that this.state.person.age is a string but in C# Age is an integer, it would be best to create a new object, parse the age, and send that in to the function.

I updated my code:

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

With thanks to @BFree and @Zied Hf .

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.