angular 8 如何发送允许 Cors 到 Web Api
angular8 how to send allow Cors to the Web Api
这是开放的 api,我正在尝试使用 URL 获取数据。但是我收到了这个错误。我无法将后端设置为允许本地主机。我有什么选择可以让它发挥作用?
错误
has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
我试过的
let header = new HttpHeaders();
header.set("Access-Control-Allow-Origin", "*");
const URL =
"url here ";
return this.http.get(URL, { headers: header })
.pipe(map(res => res));
基本上您想要访问配置为拒绝来自不同源客户端的请求的服务器。
IMO 你有两个选择。
- 请求 API 开发人员允许您请求。在这种情况下,API 将更改为允许来自您的应用程序的请求。服务器端实现因平台而异。例如.Net Core 参考 this 文章。
- 如果以上选项不适合你(API 开发者拒绝这样做)那么使用 JSONP 绕过 CORS。
例如下面是来自 Kunal Tandon 博客的示例代码。
<head>
<script>
var myFunc = function(data) {
console.log(data);
}
</script>
<script src="xyz.com?wrap=myFunc"></script>
参考Understanding JSON, JSONP, CORS, and bypassing CORS with JSONP了解更多信息。
我强烈建议您更改 API,因为这是正确的方法。 JSONP 只是一种解决方法。
这是开放的 api,我正在尝试使用 URL 获取数据。但是我收到了这个错误。我无法将后端设置为允许本地主机。我有什么选择可以让它发挥作用?
错误
has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
我试过的
let header = new HttpHeaders();
header.set("Access-Control-Allow-Origin", "*");
const URL =
"url here ";
return this.http.get(URL, { headers: header })
.pipe(map(res => res));
基本上您想要访问配置为拒绝来自不同源客户端的请求的服务器。
IMO 你有两个选择。
- 请求 API 开发人员允许您请求。在这种情况下,API 将更改为允许来自您的应用程序的请求。服务器端实现因平台而异。例如.Net Core 参考 this 文章。
- 如果以上选项不适合你(API 开发者拒绝这样做)那么使用 JSONP 绕过 CORS。
例如下面是来自 Kunal Tandon 博客的示例代码。
<head>
<script>
var myFunc = function(data) {
console.log(data);
}
</script>
<script src="xyz.com?wrap=myFunc"></script>
参考Understanding JSON, JSONP, CORS, and bypassing CORS with JSONP了解更多信息。
我强烈建议您更改 API,因为这是正确的方法。 JSONP 只是一种解决方法。