【发布时间】:2020-08-11 04:46:09
【问题描述】:
我有一个 Angular 应用程序正在运行,它使用外部 api 来获取国家/地区 ISO。 此 API 使用 https,它给了我一个错误。
问题是:当我在我的 Angular 本地环境中使用代理时,将 /iso-api/ 映射到真实的 url 就可以了。
"/iso-api/*": {
"target": "https://www...",
"pathRewrite": { "^/iso-api": "" },
"secure": false,
"changeOrigin": true,
"logLevel": "debug"
}
但我希望它在生产中工作,所以我想使用真实的 url。
在我的服务器中,我已经返回了 Access-Control-Allow-Origin: * 标头。
我尝试使用 ssl 运行 angular 服务器(因为外部 api 使用 https),但我收到了同样的错误。
我知道一个解决方案是在服务器中实现代理,但我认为不应该这样做,并且可能有一种方法可以从前端检索这些数据。 请帮忙。
响应
在 Firefox 中,请求以 200 OK 结束并返回数据,但抛出 CORS 错误,我无法从应用程序访问数据:CORS header 'Access-Control-Allow-Origin' missing
常规
Request URL: https://www...
Referrer Policy: no-referrer-when-downgrade
请求标头
:method: GET
:scheme: https
accept: application/json, text/plain, */*
accept-encoding: gzip, deflate, br
accept-language: es-ES,es;q=0.9,en;q=0.8
origin: http://localhost:4200
referer: http://localhost:4200/app/login
sec-fetch-dest: empty
sec-fetch-mode: cors
sec-fetch-site: cross-site
响应标头
accept-ranges: bytes
cache-control: max-age=0
content-encoding: gzip
content-language: en-US
content-length: 68356
content-type: application/json
date: Mon, 27 Apr 2020 14:49:30 GMT
expires: Mon, 27 Apr 2020 14:49:30 GMT
referrer-policy: strict-origin-when-cross-origin
server-timing: cdn-cache; desc=HIT
server-timing: edge; dur=1
server-timing: ACTT;dur=0,ACRTT;dur=88
set-cookie: ... expires=Mon, 27 Apr 2020 16:49:30 GMT; max-age=7200; path=/; domain=...; HttpOnly
set-cookie: ... Domain=...; Path=/; Expires=Mon, 27 Apr 2020 18:49:30 GMT; Max-Age=14400; HttpOnly
set-cookie: ... Domain=...; Path=/; Expires=Tue, 27 Apr 2021 14:49:30 GMT; Max-Age=31536000; Secure
status: 200
vary: Accept-Encoding
更新
Angular 服务代码
import { HttpClient } from '@angular/common/http';
...
constructor(
private _http: HttpClient,
private _errorUtil: ErrorUtilService,
private _converter: StoreConverter
) {}
...
getCountries(): Observable<CountryWithLanguages[]> {
return this._http.get<GetStoresResponse>(API.storeUrl).pipe(
catchError(this._errorUtil.handle),
map(result => result.stores),
switchMap(stores => stores),
filter(this._isActiveStore),
map(store => this._converter.toView(store)),
toArray()
);
}
为了为我使用 Angular 开发服务器的应用程序提供服务,我没有手动添加“Access-Control-Allow-Origin”标头,但是在浏览器中,我看到它正在被添加。
angular.json
"serve": {
"builder": "@angular-devkit/build-angular:dev-server",
"options": {
"browserTarget": "push-web-app:build",
"proxyConfig": "src/proxy-local.conf.json"
},
}
【问题讨论】:
-
那么您是从本地服务器调用生产 API 吗?出现 err_failed 错误但仍然有响应标头有点奇怪。您在控制台中没有其他错误?
-
那么可能是愚蠢的问题,但是您是否尝试过使用 fetch 或 ajax?只是想看看您是否可以查明问题的确切位置?
-
这是一个开放的 API,而不是我管理的生产应用程序,它在从浏览器访问 url 时工作。控制台中没有错误,只有网络选项卡中的消息......我尝试使用 fetch 但同样的情况发生了。我认为问题不在于 http get 请求,而在于浏览器限制 cors
-
您可能想尝试使用 Firefox devtools 来检查请求——因为不幸的是,在许多不同的情况下,Chrome devtools 不再公开某些请求和响应详细信息。例如,请参阅stackoverflow.com/q/57410051/441757。
-
所以你的问题的答案是你需要在你的远程服务器的生产环境中设置你自己的代理。如果您不拥有 API 服务器,这是绕过 CORS 的唯一方法。您使用的是哪种网络服务器? Nginx?
标签: javascript angular https http-headers