繁体   English   中英

localhost:4200 已被 CORS 策略阻止:请求的资源上不存在“Access-Control-Allow-Origin”标头

[英]localhost:4200 has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource

我正在调用 2 个 GitHub API,但是当我在控制台中打印响应时出现上述错误。 我用谷歌搜索错误并尝试通过创建 proxy.json 文件和修改 package.json 文件来修复它,但它没有修复错误。

 export class HomeComponent implements OnInit { pythonJD:any[]; javaJD:any[]; constructor(private service: GithubService) { } ngOnInit() { this.python() this.java() } python() { this.service.getPython().subscribe(res => { this.pythonJD = res; console.log(res) }); } java() { this.service.getJava().subscribe(res => { this.javaJD = res; console.log(res) }); } }

 export class GithubService { constructor(private http:HttpClient) { } getPython():Observable<any>{ return this.http.get('https://jobs.github.com/positions.json?description=python&location=new+york'); } getJava():Observable<any>{ return this.http.get('https://jobs.github.com/positions.json?description=java&location=new+york'); } }

CORS固定在api端。 https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS

出于安全原因,浏览器会限制从脚本发起的跨域 HTTP 请求。 例如,XMLHttpRequest 和 Fetch API 遵循同源策略。 这意味着使用这些 API 的 Web 应用程序只能从加载应用程序的同一来源请求资源,除非来自其他来源的响应包含正确的 CORS 标头。

由于您不控制 github,因此您无法在客户端添加 CORS 标头,因此您需要配置一个代理来解决该问题。

您可以使用本指南为本地测试配置 angular cli: https : //juristr.com/blog/2016/11/configure-proxy-api-angular-cli/

还检查angular-cli 服务器 - 如何将 API 请求代理到另一台服务器? 官方文档

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM