我收到“(未知 url)的 Http 失败响应:0 未知错误";而不是 Angular 中的实际错误消息 [英] I get "Http failure response for (unknown url): 0 Unknown Error" instead of actual error message in Angular

查看:43
本文介绍了我收到“(未知 url)的 Http 失败响应:0 未知错误";而不是 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"标头.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.`

这意味着来自后端服务器的响应缺少 Access-Control-Allow-Origin 标头,即使后端 nginx 配置为使用 add_header 指令.

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' 总是;

正确配置后端后,我可以访问 Angular 代码中的实际错误消息.

Once the backend was correctly configured I could access actual error message in Angular code.

这篇关于我收到“(未知 url)的 Http 失败响应:0 未知错误";而不是 Angular 中的实际错误消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆