INFOSYS INFOSYS - 4 years ago 298
HTTP Question

Angular 2 Http Get Request header issue

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.

Answer Source

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())
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download