【问题标题】:Need help to solve 400 bad request需要帮助解决 400 错误请求
【发布时间】:2021-09-10 17:15:17
【问题描述】:

我试图获取一个给定数据到服务器中的 POST 方法 getNumbers,它有一个参数 id,它只是返回 id 用于调试目的。所以在客户端我做如下:

 documentClickHandler=(number)=> {
    const requestOptions = {
      method: 'POST',
      headers: { 
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({ id: number })
    };
    fetch("http://localhost:5000/api/Documents/GetNumber", requestOptions)
        .then(response => response.json())
        .then(result => console.log(result))
        .catch(error => { console.log('request failed', error); });
  }

Which only has the purpuse to give the id to the getNumber method in the server:


[HttpPost("GetNumber")]
public string GetNumber([FromBody] string id)
       return id;
} 

This gives me an error (400 bad request) and I dont know how to solve it. Any ideas? Im in desperate need of help.

【问题讨论】:

  • 您可以使用浏览器中的调试工具查看发送到服务器的请求吗?
  • @AliK id 没有发送到服务器
  • 看来你没有在任何地方传递 id 你只是声明它 id 将使用 {id:'abc'} 之类的东西传递所以试试这个而不是 id:number。
  • @AliK 我认为问题在于服务器从不从客户端接收 id。当客户端单击一个表时,它会控制台记录 id,但服务器从不接收该 id,我不明白
  • 您是否在控制器构造函数上放置了断点,以确保在您开始调用时会命中控制器?

标签: c# asp.net asp.net-mvc asp.net-core .net-core


【解决方案1】:

从您的代码中删除单词“数字”。是保留字

试试这个代码:

 documentClickHandler=(documentId)=> {

   var id="123"; // try this value at first, after this use your value

    const requestOptions = {
      method: 'POST',
  
      body: {id: id}
    };
    fetch("http://localhost:5000/api/Documents/GetNumber", requestOptions)
        .then(response => response.json())
        .then(result => console.log(result))
        .catch(error => { console.log('request failed', error); });
  }

和行动

[Route("~/api/Documents/GetNumber")]
public string GetNumber( string id)
       return id;
} 

【讨论】:

  • 我试过了(区别:var id = number),但还是不行。也许数字是 int?
  • 请尝试我的答案中的代码并告诉我
  • 嗯,我现在得到 415(不支持的媒体类型)
  • 现在我得到:request failed SyntaxError: Unexpected end of JSON input
  • 现在开始行动了吗?如果是,Id 值是多少?
【解决方案2】:

请在这里找到通过 Postman 调用 HttpPost 方法的示例:

只是通过你的身体:

body: JSON.stringify(id)

【讨论】:

  • 我已经做到了 + 在服务器端的参数中添加了 [FromBody],现在我得到 415 Unsupported media type。这个我真的不明白,应该很简单。
  • 服务器唯一做的事情如下: [HttpPost("GetDocument")] public string GetNumber([FromBody] string id) { return id; }
  • 在客户端中,我所做的正是评论你的人所做的。现在我收到错误 415
  • 请尝试使用正文:JSON.stringify(id)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-09
  • 1970-01-01
  • 1970-01-01
  • 2021-12-11
  • 1970-01-01
相关资源
最近更新 更多