"JSON syntax error: unexpected number" in Angular when requesting a hash number from Spring

"JSON syntax error: unexpected number" in Angular when requesting a hash number from Spring

每次我尝试从 Spring API 在 Angular 11 上调用字符串时,我都会收到上述错误。我明白这个错误意味着我基本上是试图用不正确的语法解析 JSON,但我将一个字符串从我的 API 发送到 Angular 并获取该字符串,然后将其分配(或订阅)到一个字符串变量。我不知道 JSON.parse() 在哪里发生,我想禁用它或一起避免错误。

这是我的 Angular 11 代码。

Block.services.ts


  public getBlockHash(height:Number): Observable<string> {
    return this.http.get<string>(`${this.apiServerUrl}/blockhash/${height}`)
  }


block.component.ts

        public getBlockHash(height:Number){
    let result = this.service.getBlockHash(height)
    console.log(result)
    result.subscribe((data)=> this.blockHash = data)
  }

这是 Spring 代码。

block.controller

    @GetMapping("/blockhash/{height}")
public String getBlockHash(@PathVariable int height) {
    String hashCode = service.getBlockHash(height);
    return hashCode;
}

blockservice.java

public String getBlockHash(int number) {
    String result = RPCRequest.rpcPost(GETBLOCKHASH, number);

    BaseEntity<String> baseEntity = JSONObject.parseObject(result,
            new TypeReference<BaseEntity<String>>() {
            });
    return baseEntity.getResult();
}

您可以设置一个选项以避免将响应解析为 JSON 格式(默认)并将其作为纯文本获取。

尝试通过添加选项更改 Angular Http 调用:{responseType: 'text'};像这样:

 public getBlockHash(height:Number): Observable<string> {
   return this.http.get(`${this.apiServerUrl}/blockhash/${height}`, {
     responseType: 'text'
   })
 }