首页 > 解决方案 > 由于 CORS,第 3 方 API 拒绝 HttpClient 获取请求 - 在浏览器和 powershell 中工作

问题描述

正如标题所述。我在使用 CORS 并在简单的 GET 请求上使用 3rd 方 API 时遇到了很多问题。

在我的浏览器和 powershell 中,我可以直接使用相同的 URL 访问 API 并获得 JSON 数据。当我使用 HttpClient 将其包装到 Angular 请求中时,我收到了 CORS 错误。

我无法修改服务器,也没有为我的用例找到任何合适的答案。

在检查网络流量后,我尝试修改我的标头以匹配我的浏览器发送的内容:

return this._http.get<FullResponse>(finalEndpoint,
      {
        headers: new HttpHeaders({
          'Host': 'api.<third party>.com',
          'Accept-Encoding': 'gzip, deflate, br',
          'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
          'Cache-Control': 'max-age=0',
          'Connection': 'keep-alive'
        })
      });

但我得到错误:

Refused to set unsafe header "Host"
Refused to set unsafe header "Accept-Encoding"
Refused to set unsafe header "Connection"

以及仍然收到 CORS 错误。

Access to XMLHttpRequest at 'https://<GET URL>' from origin 'Localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

我有哪些选择?

标签: angular

解决方案


不允许设置 Host、Accept-Encoding 和 Connection 标头。出于安全原因,它们只能由用户代理设置。请参阅禁止标头名称列表。您应该尝试找出使用 HttpClient 发送请求时收到的原始 CORS 错误。

更新:

由于您无法联系第三方来更改配置,因此另一种选择是使用不同的服务器来代理 API 请求。如果您已经在 xyz.com 上拥有服务器,那么您可以创建一个类似 xyz.com/3rdPartyAPI 的端点并在那里发送您的请求。然后在服务器上,您可以使用 curl 或 wget 或其他任何方式以通常的方式请求内容,然后将响应转发回客户端。


推荐阅读