Home > other >  Getting 400 from Axios Post request
Getting 400 from Axios Post request

Time:05-28

I have a dotnet core webapi backend and on front end react typescript. I have one endpoint in which I create a user, but when I am submitting a response, I get 400 bad request errors on the browser console. For detail, I saw in the network tab it's saying: errors: {Name: ["The Name field is required."]}

Here is my Axios post request:

const res = await axios.post(
            `$localhost:5000/api/User`, {
              body: {Name: "test", Username: "testuser" },
              headers: { "Content-Type": "application/json" },
          }

on back-end

public async Task<ActionResult> Post([FromBody] UserDto dto)
{

}

UserDto contains three properties one "Age" is optional two are required "Name" and "Username"

the same request use Post man is working but not working through Axios

CodePudding user response:

For body use data in axios -

data: {
    Name: "test",
    "username": "testuser" // This is the body part
}

The the request becomes -

const res = await axios.post(
            `$localhost:5000/api/User`, {
              data: {Name: "test", Username: "testuser" },
              headers: { "Content-Type": "application/json" },
          }

CodePudding user response:

// send a POST request
axios({
  method: 'post',
  url: '/login',
  data: {
    firstName: 'Finn',
    lastName: 'Williams'
  }
});

Axios will automatically convert the data to JSON and send it as the request body.

  • Related