我收到“针对(未知网址):0未知错误的Http错误响应";而不是Angular中的实际错误消息 [英] I get "Http failure response for (unknown url): 0 Unknown Error" instead of actual error message in Angular
问题描述
我正在使用Angular 4 HttpClient
将请求发送到外部服务.这是一个非常标准的设置:
I'm using Angular 4 HttpClient
to send requests to external service. It is a very standard setup:
this.httpClient.get(url).subscribe(response => {
//do something with response
}, err => {
console.log(err.message);
}, () => {
console.log('completed');
}
问题是,当请求失败时,我会看到一个通用的
控制台中的Http failure response for (unknown url): 0 Unknown Error
消息.同时,当我检查Chrome中失败的请求时,我可以看到响应状态为422,并且在预览"选项卡中,我看到了描述失败原因的实际消息.
The problem is, when the request fails I see a generic
Http failure response for (unknown url): 0 Unknown Error
message in console. Meanwhile, when I inspect the failed request in chrome I can see the response status is 422, and in the "preview" tab I see the actual message desribing failure cause.
如何访问我在chrome开发工具中看到的实际响应消息?
How do I access the actual response message I can see in chrome dev tools?
下面是显示该问题的屏幕截图:
Here's a screenshot demonstrating the problem:
推荐答案
问题与 CORS .我注意到Chrome控制台中还有另一个错误:
The problem was related to CORS. I noticed that there was another error in Chrome console:
所请求的资源上没有"Access-Control-Allow-Origin"标头.因此,不允许访问来源" http://localhost:4200 .响应的HTTP状态代码为422.
No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access. The response had HTTP status code 422.`
This means the response from backend server was missing Access-Control-Allow-Origin
header even though backend nginx was configured to add those headers to the responses with add_header
directive.
但是,此指令仅在响应代码为20X或30X时才添加标头.在错误响应上,标头丢失.我需要使用always
参数来确保添加标头,而不考虑响应代码:
However, this directive only adds headers when response code is 20X or 30X. On error responses the headers were missing. I needed to use always
parameter to make sure header is added regardless of the response code:
add_header 'Access-Control-Allow-Origin' 'http://localhost:4200' always;
一旦正确配置了后端,我就可以使用Angular代码访问实际的错误消息.
Once the backend was correctly configured I could access actual error message in Angular code.
这篇关于我收到“针对(未知网址):0未知错误的Http错误响应";而不是Angular中的实际错误消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!