saswat saubhagya
saswat saubhagya

Reputation: 133

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

Upvotes: 0

Views: 464

Answers (1)

itminus
itminus

Reputation: 25360

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(string aa)

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([FromBody]Payload 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([FromBody]string 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.

Upvotes: 1

Related Questions