应用上面这段代码在 Angular 利用里进行 HTTP 拜访:
this.httpClient.get(url).subscribe(response => { //do something with response}, err => { console.log(err.message);}, () => { console.log('completed');}
问题是,当申请失败时,我在控制台中看到 (unknown url): 0 Unknown Error
音讯的通用 Http 失败响应。 同时,当我在 chrome 中查看失败的申请时,我能够看到响应状态为 422,并且在预览
选项卡中,我看到了形容失败起因的理论音讯。
如何拜访我能够在 chrome 开发工具中看到的理论响应音讯?
这是演示问题的屏幕截图:
[图片]
一种可能的起因是申请的资源上不存在“Access-Control-Allow-Origin”标头。 因而,不容许来自 Origin 'http://localhost:4200' 的利用拜访该资源。
这意味着来自后端服务器的响应短少 Access-Control-Allow-Origin 标头,即便后端 nginx 已配置为应用 add_header 指令将这些标头增加到响应中。
然而,此指令仅在响应代码为 20X 或 30X 时增加标头。 在谬误响应中,标头失落。 无论响应代码如何,我都须要应用 always 参数来确保增加标头:
add_header 'Access-Control-Allow-Origin' 'http://localhost:4200' always;
正确配置后端后,我能够拜访 Angular 代码中的理论谬误音讯。
除了 CORS 谬误之外,另一种可能的谬误:
我的问题是因为我应用的是 Android 平台级别 28,默认状况下禁用明文网络通信,并且我正在尝试开发指向笔记本电脑 IP(运行 API 服务器)的应用程序。 API 根本 URL 相似于 http://[LAPTOP_IP]:8081
。 因为它不是 https,所以 android webview 齐全阻止了手机/模拟器和我笔记本电脑上的服务器之间的网络传输。 为了解决这个问题,批改下列配置文件:
resources/android/xml/network_security_config.xml
<?xml version="1.0" encoding="utf-8"?><network-security-config> <!-- Set application-wide security config --> <base-config cleartextTrafficPermitted="true"/></network-security-config>
<platform name="android"> ... <edit-config file="app/src/main/AndroidManifest.xml" mode="merge" target="/manifest/application" xmlns:android="http://schemas.android.com/apk/res/android"> <application android:networkSecurityConfig="@xml/network_security_config" /> </edit-config> <resource-file src="resources/android/xml/network_security_config.xml" target="app/src/main/res/xml/network_security_config.xml" /> ....</platform>