在Angular HTTP PUT的请求正文中传递原始数据类型

时间:2019-04-04 06:33:37

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

我有一种服务方法,我需要通过请求有效负载(即主体)使用HTTP PUT请求,通过String属性将UUID传递给服务。

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

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

    // Internal Operations - TODO

    return 'SUCCESS';
}

角度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应用程序中却失败了。

1 个答案:

答案 0 :(得分:0)

您收到该错误,原因是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实现