如何解决从本地主机请求公共API的角度问题:4200
我正在尝试从公共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);
});
}
解决方法
您需要做的就是在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
以下是其工作示例:
我知道您的代码是有角度的,但出于示例的原因,原理是相同的
$.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);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。