【发布时间】: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);
});
}
【问题讨论】:
-
请对what CORS is and how it works进行一些研究,并搜索错误消息。 Stack Overflow 上有数百个关于此的问题。