【问题标题】:Angular HTTP Request Works, but HttpClient FailsAngular HTTP 请求有效,但 HttpClient 失败
【发布时间】: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 并完美运行...

【问题讨论】:

    标签: angular aws-api-gateway


    【解决方案1】:

    在后台 - 浏览器成功向您的 API 发出请求,但由于请求具有不同的来源,并且缺少 Access-Control-Allow-Origin 标头 - 由于安全原因,它被阻止,这是标准的现代网络浏览器的行为。

    您可以阅读有关 CORS 的更多信息here

    如我所见,您使用的是 AWS API Gateway - here is guide how to enable CORS at API Gateway

    编辑

    如果您启用了 CORS,状态代码为 200 并且仍然缺少 Access-Control-Allow-Origin,您可能在 API 网关上使用了 Lambda 代理集成。在这种情况下 - 您的 Lambda 负责返回标头等。

    所以响应对象应该是这样的:

    {
        ...
        "headers": {
            "Access-Control-Allow-Origin": "*",
            ...
        },
        ...
    }
    

    more info here

    【讨论】:

    • @ Michal Z. - 查看我的更新回复...所有资源都启用了 CORS,但只有调用 Lambda 的资源才会崩溃。
    • 是的,我现在明白了......无论如何 - 如果状态是 200,那么 CORS 可能有问题。
    • 这是一个 Lambda 代理集成问题...如果我关闭代理集成它会起作用,但我依赖于请求正文/参数...
    • 还有另一种可能性...如果您在 API Gateway 上使用 Lambda 代理集成 - 那么您的 Lambda 负责返回标头等。
    • 哈,你是在我点击“添加评论”后写的:D 是的,就是这样 - 看看这个:docs.aws.amazon.com/apigateway/latest/developerguide/… 你需要标题[''Access-Control-Allow-Origin'] =...
    【解决方案2】:

    据我所知,有两种选择。 第一个是修改您的后端,以便它在 Access-Control-Allow-Origin 标头中发送 localhost,第二个(对我来说更简单)是代理您的 api 调用。如果你使用 angular-cli,你可以配置它来代理你的请求,如果没有 - 你可以使用 nginx - 只需下载它,甚至不需要安装一些东西,然后修改 conf 文件(fiy)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-02-26
      • 2019-05-23
      • 2017-10-14
      • 1970-01-01
      • 1970-01-01
      • 2021-02-28
      • 2020-01-31
      相关资源
      最近更新 更多