Trying to understand why such a simple rest call api not working from localhost (using angular-cli).
This is the service code:
commandsUrl ='http://www.mocky.io/v2/...';
headers = new Headers({ 'Access-Control-Allow-Origin': '*' });
options = new RequestOptions({ headers: this.headers, withCredentials: true });
getMyList (): Observable<any> {
return this.http.get(this.commandsUrl, this.options)
.map(this.extractData)
.catch(this.handleError);
}
private extractData(res: Response) {
let body = res.json();
return body.data || { };
}
private handleError (error: Response | any) {
let errMsg: string;
if (error instanceof Response) {
const body = error.json() || '';
const err = body.error || JSON.stringify(body);
errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
} else {
errMsg = error.message ? error.message : error.toString();
}
console.error(errMsg);
return Observable.throw(errMsg);
}
The error from browser is:
XMLHttpRequest cannot load http://www.mocky.io/v2/... Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access.