【问题标题】:Error 400 Required request body is missing错误 400 缺少所需的请求正文
【发布时间】:2020-03-24 21:36:51
【问题描述】:

我有一个用 Kotlin 编写的 Spring Boot REST 端点:

@GetMapping(value="/transferDetails")
private fun transferAccountDetails(@RequestBody transferAcctDetails: TransferAccountDetails):results{

    /** Hidden logic*/

    return results(true,"Details Transferred Successfully")
}

//region Data View classes for HTTP response are defined here
data class TransferAccountDetails(val ownerKey: String, val counterPartyKey: String, val acctId: String)

上述端点所做的只是从请求正文中获取参数,并对数据库进行一些更改并最终返回成功消息。

假设我无法更改用于此端点的行为或请求类型(例如 POST 或 PathVariable),并且上面的脚本是最终的,并且已经过 Postman 测试并且可以正常工作。

在前端,我使用 Angular 并将请求发送到我的service 中的上述端点,如下所示:

  processAccountDetailsUrl = 'http://.../api/transferDetails';

  processAccountDetails(ownerKey: string, counterPartyKey: string, acctId: string) {
    this.paramsDict = {
      ownerKey: { ownerKey},
      counterPartyKey: { counterPartyKey},
      acctId: { acctId }
    };

    this.requestOptions = {
      params: new HttpParams(this.paramsDict)
    };

    return this.http.get(this.processAccountDetailsUrl , this.requestOptions);
  }

我收到以下错误 400:

{
    "timestamp": "2019-11-29T08:16:52.793+0000",
    "status": 400,
    "error": "Bad Request",
    "message": "Required request body is missing: private final com.template.webserver.results..."
    "path": "/api/transferAccountDetails"
}

requestOptions 不是将请求正文添加到 GET 请求的方法吗?如果是这样,我应该进行哪些更改才能调用 REST 端点?哪里出了问题?假设我只能编辑前端,并且后端已经过测试可以正常工作,不应进行进一步的更改。

我尝试在我的 TS 文件中创建一个与data class TransferAccountDetails 具有相同变量的接口,并尝试像return this.http.get(this.processAccountDetailsUrl , this.theInterfaceObject); 一样对其进行解析。这不起作用,因为它不是 GET 请求的类型。

【问题讨论】:

    标签: angular typescript api spring-boot kotlin


    【解决方案1】:

    不建议在 get 请求中使用 RequestBody :

    HTTP GET with request body

    https://github.com/angular/angular/issues/9927

    【讨论】:

    • 是的,我明白这一点,并且已经看到您分享的帖子。但情况是我无法更改后端所做的事情。有没有办法为前端解决这个错误?
    • 只能改前端不能改后端?
    • 是的,假设是这样,那么我在角度方面(我的 service.ts)做错了什么?
    • 你可以将请求正文更改为 requestParameter 或 pathVariable ,具体取决于它应该做什么
    • 我已经在使用requestParameter(在上面的service.ts 脚本中)不是吗(在this.requestOptions 中添加了requestParams)?我不能在角度服务上使用pathVariable,因为端点需要RequestBody,对吗?
    猜你喜欢
    • 2017-08-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-01
    • 1970-01-01
    相关资源
    最近更新 更多