0

My Angular 2 Service is calling and external api , but i am getting a error in the browser console. I tried adding headers to the Get method but still the error persists.

Service

import { Injectable } from '@angular/core';
import { Http,Headers } from '@angular/http';
import 'rxjs/add/operator/map';

@Injectable()

export class CompetitionService{

     constructor(private http:Http){

     }

    getCompetitions(){
        let headers = new Headers();
        headers.append('Access-Control-Allow-Credentials', 'true');
        headers.append('Access-Control-Allow-Methods', 'GET');
        headers.append('Access-Control-Allow-Origin', '*');
        return this.http.get('http://api.football-data.org/v1/competitions',{headers:headers}).map(response => response.json())
    }
}

console log Before Header

XMLHttpRequest cannot load http://api.football-data.org/v1/competitions. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access.

After Header XMLHttpRequest cannot load http://api.football-data.org/v1/competitions. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access.

3
  • 1
    the Access-Control headers need to be set at the server side not client.. this is a cors issue Commented Feb 6, 2017 at 9:51
  • Any way we can get around it? Commented Feb 6, 2017 at 10:00
  • depends on what type of backend you are using.. you will have to set these headers. developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS Commented Feb 6, 2017 at 10:02

1 Answer 1

1

this is CORS issue in browser and football-data api

http://api.football-data.org/docs/v1/index.html#_cors_handling

However, if you implement requests directly from Javascript, you need to add your X-Auth-Token correctly so the API gives you permission to do that

so to call api from your app, you need add header:

getCompetitions(){
    let headers = new Headers();
    let token = 'your token';
    headers.append('X-Auth-Token', token);
    return this.http.get('http://api.football-data.org/v1/competitions',{headers:headers}).map(response => response.json())
}
Sign up to request clarification or add additional context in comments.

1 Comment

Doesn't work, same error after trying your suggestion

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.