从 Spring 请求哈希数时,Angular 中出现“JSON 语法错误:意外数字”

问题描述

每次我尝试从 Angular 11 上的 Spring API 调用字符串时,都会收到上述错误。我知道这个错误意味着我基本上是在尝试解析语法不正确的 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'
   })
 }

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...