【问题标题】:Pass a primitive data type in request body in the Angular HTTP PUT在 Angular HTTP PUT 的请求正文中传递原始数据类型
【发布时间】:2019-08-25 19:35:21
【问题描述】:

我有一个服务方法,我需要通过请求负载(即正文)使用 HTTP PUT 请求通过字符串属性将 UUID 传递给服务。

Java Spring Boot API 控制器方法的签名是

@PutMapping("group/{groupId}/updateFile")
    public String deleteAgencyFile(@PathVariable("groupId") UUID reportId,@RequestBody UUID fileId) {

    // Internal Operations - TODO

    return 'SUCCESS';
}

Angular HTTP PUT 代码:

updateGroupFile() {
    const groupId: string = 'b9ddab47-56a2-11e9-8882-484d7ee28bcd';
    const fileId: string = 'c0822353-56a2-11e9-8882-484d7ee28bcd';

    const filePath = `http://localhost:3000/api/group/${groupId}/updateFile`

    return this.http.put<SimpleResponse>(filePath, fileId);
}

一旦我订阅了 Angular 方法,我就会收到错误消息:

{
   "timestamp":"2019-04-04T06:30:32.098+0000",
   "status":400,
   "error":"Bad Request",
   "message":"JSON parse error: Unrecognized token 'c0822353': was expecting 'null', 'true', 'false' or NaN; nested exception is com.fasterxml.jackson.core.JsonParseException: Unrecognized token 'c0822353': was expecting 'null', 'true', 'false' or NaN\n at [Source: (PushbackInputStream); line: 1, column: 10]",
   "path":"/api/group/b9ddab47-56a2-11e9-8882-484d7ee28bcd/updateFile"
}

我在 POSTMAN 中尝试了同样的方法,它可以工作,但在 Angular 应用程序中它失败了。

【问题讨论】:

    标签: javascript angular spring-boot angular-httpclient http-put


    【解决方案1】:

    您收到该错误是因为 put() 的第二个参数需要一个有效的 JSON。有效代码为

    updateGroupFile() {
        const groupId: string = 'b9ddab47-56a2-11e9-8882-484d7ee28bcd';
        const fileId: string = 'c0822353-56a2-11e9-8882-484d7ee28bcd';
    
        const filePath = `http://localhost:3000/api/group/${groupId}/updateFile`
    
        return this.http.put<SimpleResponse>(filePath, {fileId});
    }
    

    或者如果你想要一个特定的参数名称,那么

    return this.http.put<SimpleResponse>(filePath, {'id': fileId});
    return this.http.put<SimpleResponse>(filePath, {'uuid': fileId});
    

    等等...这也取决于您在代码中的 UUID 实现

    【讨论】:

    • 我试过这个,如果我以这种方式通过它就像{ "fileId": "c0822353-56a2-11e9-8882-484d7ee28bcd" } - 它不会接受。
    • 不接受?您仍然收到错误吗?或者它不会在后端接受?
    • 两个对象不同,API 将接受 GUID 而不是对象。
    猜你喜欢
    • 2014-09-29
    • 1970-01-01
    • 2010-11-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多