简体   繁体   English

无法将请求正文发送到JavaScript fetch()中的API端点

[英]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. 我正在尝试创建一个asp.net核心API,该API通过POST请求接收JSON字符串化对象。 To send a POST request to this API I use the JavaScript fetch() function. 要将POST请求发送到此API,请使用JavaScript fetch()函数。 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! 在POST请求的主体中,我向后端发送了一个字符串化的对象,但是当后端接收到该请求时,主体值为空! Why is this? 为什么是这样?

My JavaScript post call: 我的JavaScript通话:

  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: 我的API后端:

 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 : 那是因为您的客户端正在发送json有效负载,而服务器则需要一个纯字符串

public JsonResult supervisors_name(string aa)

As a result, the string aa is always null . 结果,字符串aa始终为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. 您可以使用JSON格式发送有效载荷并绑定参数,也可以使用String格式发送并绑定有效载荷。 But don't mix them up. 但是不要把它们混在一起。

Approach 1 (Json format): 方法1(Json格式):

create a dummy Payload class to hold the aa property: 创建一个虚拟的Payload类来保存aa属性:

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

And change the action method to accept a Payload parameter : 并更改操作方法以接受Payload参数:

[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. 如果您使用的是非API控制器,请不要忘记[FromBody]

Approach 2 (string format): 方法2(字符串格式):

In case you want to receive the json body as a plain string, you need to declare a [FromBody] string aa : 如果要以纯字符串形式接收json正文,则需要声明[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 . 客户端应发送带有Content-Type: application/json的标头的请求Content-Type: application/json

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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