admin管理员组

文章数量:1420197

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.

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.

Share Improve this question edited Sep 21, 2021 at 14:32 Indigo asked Sep 21, 2021 at 13:07 IndigoIndigo 1801 gold badge3 silver badges13 bronze badges 12
  • The reason why controller is not reached is probably there is middleware to validate the request body. Does your browser send another request like Options or Fetch together with your request to the same url? It smells like something is wrong with headers to allow body. Refer to CORS policy – Abror Abdullaev Commented Sep 21, 2021 at 13:13
  • @AbrorAbdullaev according to the Network tab it only sends PUT. I don't think anything else is being sent. Please could you expand on what I could do with CORS policy? Thanks. – Indigo Commented Sep 21, 2021 at 13:22
  • Did you check that javascript person is not null? Did you check developer tools of the browser for javascript error? – Serge Commented Sep 21, 2021 at 16:14
  • @Serge Yes I have checked that and the person object is indeed present. I have more details about what happened in the replies under the other answer. I have now e to find out that doing the request with Angular's httpClient doesn't error, however the fetch function does. – Indigo Commented Sep 21, 2021 at 16:33
  • @alalalal Did you check the Console of developer tools of browser? it usually shows javascript errors – Serge Commented Sep 21, 2021 at 16:35
 |  Show 7 more ments

2 Answers 2

Reset to default 2

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.

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

本文标签: