angular - 由于 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.
我有哪些选择?
解决方案
不允许设置 Host、Accept-Encoding 和 Connection 标头。出于安全原因,它们只能由用户代理设置。请参阅禁止标头名称列表。您应该尝试找出使用 HttpClient 发送请求时收到的原始 CORS 错误。
更新:
由于您无法联系第三方来更改配置,因此另一种选择是使用不同的服务器来代理 API 请求。如果您已经在 xyz.com 上拥有服务器,那么您可以创建一个类似 xyz.com/3rdPartyAPI 的端点并在那里发送您的请求。然后在服务器上,您可以使用 curl 或 wget 或其他任何方式以通常的方式请求内容,然后将响应转发回客户端。
推荐阅读
- git - Bamboo 用于本地存储库的正确 git url 是什么?
- go - Bazel Gazelle 错误:没有这样的包 '@org_golang_x_tools//go/analysis/internal/facts':在目录中找不到 BUILD 文件
- python - 使用 Matplotlib 比较图表中的多条线
- node.js - 当我尝试将 React 和 nodejs 与 env 变量连接起来时,看起来反应没有向 Nodejs 发送请求
- laravel - 如何在laravel中保存路由中传递的id
- python - 代码正在运行,但现在突然无法运行 - 数据框问题
- python-3.x - 结果导致文件未找到错误 GZIP HASH-LIB
- c# - 为什么后台工作人员可以启动额外的工作线程来处理 ProgressChangedEvent?
- python - 安装 Python 包以供系统广泛使用
- javascript - 代码镜像。替换文本的简单方法?