0

I am calling 2 GitHub API's but i am getting above error when I am printing the response in the console. I googled the error and tried fixing it by creating proxy.json file and modifying package.json file but it doesn't fix the error.

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');
  }
}
Athanasios Kataras
  • 25,191
  • 4
  • 32
  • 61
  • Does this answer your question? [How does Access-Control-Allow-Origin header work?](https://stackoverflow.com/questions/10636611/how-does-access-control-allow-origin-header-work) – Madhawa Priyashantha Dec 26 '19 at 10:07

1 Answers1

1

CORS is fixed on the api side. https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS

For security reasons, browsers restrict cross-origin HTTP requests initiated from scripts. For example, XMLHttpRequest and the Fetch API follow the same-origin policy. This means that a web application using those APIs can only request resources from the same origin the application was loaded from, unless the response from other origins includes the right CORS headers.

Since you don't control github, so you can't add the CORS header on the client side, you need to configure a proxy to fix that.

You can configure angular cli for local testing using this guide: https://juristr.com/blog/2016/11/configure-proxy-api-angular-cli/

Check also angular-cli server - how to proxy API requests to another server? for official documentation

Athanasios Kataras
  • 25,191
  • 4
  • 32
  • 61