【问题标题】:Angular httpClient can't get a String object [duplicate]Angular httpClient无法获取字符串对象[重复]
【发布时间】:2019-01-14 11:34:09
【问题描述】:

我正在使用 Angular 6 从我的 Java REST 应用程序中获取字符串,但无法解析/获取字符串

REST API 服务工作正常,它按预期返回字符串,但在浏览器控制台中出现此错误

“SyntaxError: JSON.parse 中位置 4 的 JSON 中的意外标记 X”

我认为这与标题的内容类型有关

我已经尝试更改响应类型,但我无法发送我的数据。

login(userDTO:UserDTO):Observable<String> {
    let header:HttpHeaders = new HttpHeaders({
      'Content-type' : 'application/json',
    });
    return this.httpClient.post<String>('http://localhost:8080/login',  
userDTO, {headers: header});
  }

编辑: “你从哪里得到 String 对象?你应该使用字符串文字。- Edric 2 分钟”

我从一个返回字符串 Java 对象的 REST Java 服务中获取它

【问题讨论】:

  • 你从哪里得到String 对象?您应该使用 string 文字。
  • 查看我链接的副本。在您的情况下,删除 &lt;String&gt; 并添加 responseType 属性:return this.httpClient.post('http://localhost:8080/login', userDTO, {headers: header, responseType: 'text'});

标签: angular typescript rest http httpclient


【解决方案1】:

您需要期待string 对象而不是String 对象。 换个方式

return this.httpClient.post<String>('http://localhost:8080/login',
userDTO, {headers: header});

return this.httpClient.post<string>('http://localhost:8080/login',
userDTO, {headers: header});

期望返回类型也为Observable&lt;string&gt;

【讨论】:

    猜你喜欢
    • 2016-05-31
    • 2019-04-30
    • 2015-08-28
    • 1970-01-01
    • 1970-01-01
    • 2018-08-03
    • 2019-09-11
    • 1970-01-01
    • 2014-02-27
    相关资源
    最近更新 更多