【发布时间】:2018-07-03 17:07:44
【问题描述】:
我已经构建了一个启用 CORS 的 API,但是 HttpClient 在客户端向我抛出了一些奇怪的东西。当我查看 Chrome 中的“网络”选项卡时,我看到了对我的请求的正确响应,但由于我在本地运行,Angular 会引发 CORS 错误。
这是我的代码:
public search(data: string): Promise<any> {
const url = `${Configuration.ENDPOINTS.APP}`, headers = new HttpHeaders({ 'x-api-key': 'abcd...' });
const body = { data: data };
return this._http.post<any>(url, body, { headers: headers }).toPromise();
}
/// View Logic
search("test").then(console.log).catch(console.error)
运行此代码,我在 Chrome 的“控制台”选项卡上收到以下错误:
Failed to load https://abcd.execute-api.us-east-1.amazonaws.com/v1/: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8100' is therefore not allowed access.
HttpErrorResponse
{
"headers": {
"normalizedNames": {},
"lazyUpdate": null,
"headers": {}
},
"status": 0,
"statusText": "Unknown Error",
"url": null,
"ok": false,
"name": "HttpErrorResponse",
"message": "Http failure response for (unknown url): 0 Unknown Error",
"error": {
"isTrusted": true
}
}
但是,如果我查看“网络”选项卡,就会得到以下响应:
Headers
content-length: 16865
content-type: application/json
date: Wed, 04 Apr 2018 17:34:28 GMT
status: 200
via: 1.1 cae81d5ff1d682b28f2deabdd94777d4.cloudfront.net (CloudFront)
x-amz-apigw-id: E07puFICPHcFYCA=
x-amz-cf-id: -UYlYK_yC8cUVZF2OnRFcUb_fIjcRrgMuvpU3ADdbpyEvPZ-nUJXNA==
x-amzn-requestid: 6d3a0533-382e-11e8-ad31-b124cb8b7a9a
x-amzn-trace-id: sampled=0;root=1-5ac50ca4-2411d1b5cb7d1af6232883a6
x-cache: Miss from cloudfront
Response
{
meta: { ... }
data: [ ... ]
}
出于安全原因,我在回复中省略了一些内容。
有人知道发生了什么吗?为什么网络选项卡可以工作,而 Angular 不行?
编辑:这是 AWS API 网关的一部分。所有资源都启用了 CORS,但由于某种原因,与 Lambda 集成的端点向我抛出了这个问题。其他端点直接连接到 DynamoDB 并完美运行...
【问题讨论】: