简体   繁体   中英

Unable to send request body to API endpoint in a JavaScript fetch()

I am trying to create an asp.net core API which receives a JSON stringified object through a POST request. To send a POST request to this API I use the JavaScript fetch() function. In the body of the POST request, I send a stringified object to the backend, but when the backend receives the request the body value is empty! Why is this?

My JavaScript post call:

  function BindSupervisor() { (() => { const rawResponse = fetch('mu_url', { method: 'POST', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' }, body: JSON.stringify({aa:'W15'}) }); const content = rawResponse.json(); console.log(content); })(); } 

My API backend:

 public JsonResult supervisors_name(string aa) { // My logic return Json (supervisors); } 

Thank you in Advance.

I send a stringified object to the backend, but when the backend receives the request the body value is empty

That's because your client is sending a json payload, while the server is expecting a plain string :

public JsonResult supervisors_name()

As a result, the string aa is always null .


How to fix :

You could send the payload and bind the parameter both in JSON format, or you could also send and bind the payload both in String format. But don't mix them up.

Approach 1 (Json format):

create a dummy Payload class to hold the aa property:

public class Payload {
    public string Aa {get;set;}
}

And change the action method to accept a Payload parameter :

[HttpPost]
public JsonResult supervisors_name2( data)
{
    // now you get the data.Aa
    return Json (supervisors);
}

Don't forget the [FromBody] if you're using a non-api controller.

Approach 2 (string format):

In case you want to receive the json body as a plain string, you need to declare a [FromBody] string aa :

[HttpPost]
public JsonResult supervisors_name( aa)
{
    // now you get the aa as string
    return Json (supervisors);
}

The client should send the request with a header of Content-Type: application/json .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM