Home > front end >  I'm receiving a 400 bad request error: "A non-empty request body is required" from my
I'm receiving a 400 bad request error: "A non-empty request body is required" from my

Time:09-22

Everytime I make a fetch request from my frontend using the following js code I receive a 400 Bad request status. The body of the response has an error object saying: "A non-empty request body is required".

When I inspect the request section on my devtools network tab it says "no payload for this request". So it looks to me it's not sending the body section of my Fetch.

It does reach the .then() method afterwards.

This is the Typescript Code:

fetch(`api/person/${person.id}`, {
  method: "PUT",
  headers: {
    "Content-Type": "application/json"
  },
  body: JSON.stringify(person)
})
  .then(() => this.router.navigate(["/"]))

this is the C# backend:

[HttpPut("{id}")]
public IActionResult Put(int id, Person person)
{
    person.Id = id;

    try
    {
       var updatedPerson = _personRepository.Update(person);
       if (updatedPerson != null)
       {
            return Ok(updatedPerson);
       }

       return NotFound();
    }
    catch (ArgumentNullException)
    {
        return BadRequest();
    }
}

Note that the request doesn't even reach this controller. No break points will be reached if I place any here.

This is a single page application I run from Visual Studio 2019.

It works with postman however, returning the 200 Ok status code and an object back, and reaching backend breakpoints. The request URL contains the int id and the body containing a Json object.

CodePudding user response:

Okay this is not a question that has a clear answer. Here are steps you could need to take to find out:

  • Make sure in your fetch request the argument person is really exist, just do console.log(person) before fetch

  • Make sure server accepts 'application/json' type content. Though in this case the response code should have been different.

  • Check the response headers, and are the origins of back end and front end are the same? What you need to see are the following:

    Access-Control-Allow-Headers: *
    Access-Control-Allow-Methods: PUT
    Access-Control-Allow-Origin: *
    
    

Postman works as a native app on your PC and has different way of sending requests rather than your browser, sometimes this causes unclear results.

CodePudding user response:

Here's a way to test what is happening.

  1. Go to your main web site (http://localhost:5001 or whatever) in your browser
  2. Open up Browser Dev Tools (F12 in most browsers)
  3. copy / paste the following fetch (code below) into your Dev console & press

What happens? Do you get data back (printed in console)? This will probably get you to the next step you need to take.

fetch("api/person/1")
.then(response => response.json())
.then(data => console.log(data));
  • Related