【问题标题】:Angular problem requesting public API from localhost:4200从 localhost:4200 请求公共 API 的角度问题
【发布时间】:2020-12-15 13:38:39
【问题描述】:

我正在尝试从公共 API 获取 JSON 数据: https://www.gov.uk/api/content/government/collections/local-restrictions-areas-with-an-outbreak-of-coronavirus-covid-19

但应用程序因 CORS 问题而大喊大叫。

我不确定是否有什么办法可以解决这个问题。

我的错误信息

Access to XMLHttpRequest at 'https://www.gov.uk/api/content/government/collections/local-restrictions-areas-with-an-outbreak-of-coronavirus-covid-19' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

我的功能

    getLocalAreaNews(): Observable<any> {
        const url     = this.ApiUrl + '/government/collections/local-restrictions-areas-with-an-outbreak-of-coronavirus-covid-19';
        const headers = new HttpHeaders()
            .set('Access-Control-Allow-Origin', '*');

        console.log(url);

        return this.http.get<any>(url, {
           headers: headers
        });

    }


    ngOnInit(): void {
        this.GovApi.getLocalAreaNews().subscribe((data) => {
            console.log(data);
        });
    }

【问题讨论】:

标签: angular api get


【解决方案1】:

您所要做的就是在您的 URL 前面加上:

https://cors-anywhere.herokuapp.com/

喜欢:

const url     = "https://cors-anywhere.herokuapp.com/"
+ this.ApiUrl + "/government/collections/local-restrictions-areas-with-an-outbreak-of-coronavirus-covid-19

这是它的工作演示:

Online Demo

我知道你的代码是有角度的,但为了这个例子,原理是一样的

$.ajax({ type: "GET", url: "https://cors-anywhere.herokuapp.com/https://www.gov.uk/api/content/government/collections/local-restrictions-areas-with-an-outbreak-of-coronavirus-covid-19", contentType: 'application/json', dataType: 'json' }).done(function (result) {
            console.log(result);
 }).fail(function (err) {
     console.log("Error =>", err);
});
&lt;script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"&gt;&lt;/script&gt;

【讨论】:

  • 真好!谢谢@Dalarzo 知道当应用程序部署到生产环境时如何处理这个问题,还是这个问题只发生在本地环境中?
  • CORS Anywhere 是一个 NodeJS 反向代理,它将 CORS 标头添加到托管在 herokuapp 中的代理请求中。问题是关于标题的,很可能你也会在 PROD 中遇到问题
  • 你可能想试试这个:medium.com/better-programming/…
  • 这个网址是一个演示,你应该根据他们的文档自行托管它:github.com/Rob--W/cors-anywhere。演示服务器 CORS Anywhere 的公开演示可在cors-anywhere.herokuapp.com 获得。仅提供此服务器,以便您可以轻松快速地试用 CORS Anywhere。为确保该服务对所有人可用,每个周期的请求数量是有限的,但来自某些明确列入白名单的来源的请求除外。如果您预计会有大量流量,请托管您自己的 CORS Anywhere 实例...
猜你喜欢
  • 2019-09-10
  • 1970-01-01
  • 1970-01-01
  • 2021-06-13
  • 2015-02-20
  • 1970-01-01
  • 2017-10-16
  • 2021-04-20
  • 1970-01-01
相关资源
最近更新 更多