纯/文本的 Angular 8/httpclient 错误响应,无法解析响应
Posted
技术标签:
【中文标题】纯/文本的 Angular 8/httpclient 错误响应,无法解析响应【英文标题】:Angular 8/httpclient error response for plain/text, cannot parse response 【发布时间】:2020-04-11 01:46:40 【问题描述】:在浏览器上显示此错误。我正在测试 Springboot 并尝试实现不记名身份验证。我将令牌作为文本返回。
error: Object error: SyntaxError, text: "Bearer eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJpdm9uZXRlYnJ1bmFAYm9sLmNvbS5iciIsImV4cCI6MTU3NzUzODgzMH0.oUMmxd65XJtdfLKmlhbczp3-u1LIGzfzCla0RyKeIy0PKlq4upxd_7NtxfMspFCtpniuqsiwpGjpH_yWTrDbqg"
headers: …
lazyInit: function lazyInit()
lazyUpdate: null
normalizedNames: Map(0)
<prototype>: Object …
message: "Http failure during parsing for http://localhost:8080/login"
name: "HttpErrorResponse"error: Object error: SyntaxError, text: "Bearer eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJpdm9uZXRlYnJ1bmFAYm9sLmNvbS5iciIsImV4cCI6MTU3NzUzODgzMH0.oUMmxd65XJtdfLKmlhbczp3-u1LIGzfzCla0RyKeIy0PKlq4upxd_7NtxfMspFCtpniuqsiwpGjpH_yWTrDbqg"
headers: …
lazyInit: function lazyInit()
lazyUpdate: null
normalizedNames: Map(0)
<prototype>: Object …
message: "Http failure during parsing for http://localhost:8080/login"
name: "HttpErrorResponse"
我的服务是这样设置的:
logar (credenciais: Credenciais): Observable<any>
const httpOptions =
headers: new HttpHeaders('Content-Type': 'application/json', accept: 'text/plain')
;
return this.http.post("http://localhost:8080/login", credenciais, httpOptions);
我不是 http 标头方面的专家,但我发现 Spring 的响应没有内容类型很奇怪。回复如下:
HTTP/1.1 200
Access-Control-Allow-Credentials: true
Access-Control-Allow-Origin: http://localhost:4200
Vary: Origin
Access-Control-Allow-Methods: *
Access-Control-Allow-Headers: Origin, X-Requested-With, Authorization, Content-Type, Accept, X-CSRF-TOKEN
Access-Control-Max-Age: 3600
Authorization: Bearer eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJpdm9uZXRlYnJ1bmFAYm9sLmNvbS5iciIsImV4cCI6MTU3NzUzOTc5NH0.-YOzULQnPD6aDIoxzqOQbxbCOpZChJni2FKCazLr-0jTe6ExwwAT8L9V4m5qUoJ68jDz71aE2lrbSbmWPciWCQ
X-Content-Type-Options: nosniff
X-XSS-Protection: 1; mode=block
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Pragma: no-cache
Expires: 0
X-Frame-Options: DENY
Content-Length: 182
Date: Wed, 18 Dec 2019 13:29:54 GMT
Keep-Alive: timeout=60
Connection: keep-alive
我可以在浏览器控制台上看到来自服务器的响应。问题是解析响应。响应可用,但我无法操纵它。我该如何修改这个?
【问题讨论】:
【参考方案1】:尝试将 responseType: 'text' 添加到 http 选项列表中。
const httpOptions =
headers: new HttpHeaders('Content-Type': 'application/json', accept: 'text/plain')
responseType: 'text'
;
【讨论】:
以上是关于纯/文本的 Angular 8/httpclient 错误响应,无法解析响应的主要内容,如果未能解决你的问题,请参考以下文章
使用 $http 发送 JSON 导致 Angular 发送文本/纯内容类型
文本/纯文件下载的 Angular http$ 响应失败,并出现 SyntaxError:JSON 中的意外数字