I am working on an Angular 2 application that interacts with an external API to fetch data.
Unfortunately, I do not have the authority to modify the API code. However, I can make changes to the TypeScripts and Lite-Server configuration.
Encountered Error: XMLHttpRequest cannot load .... No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4000' is therefore not allowed access.
I have researched CORS extensively but I am unsure how to integrate it into my code. What would be the simplest way to resolve this issue?
Here is my service:
import { Injectable } from '@angular/core';
import { Http, Response, Headers, RequestOptions } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import { Page } from './page';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
@Injectable()
export class ProductService {
private urlPage = 'http://api.zanox.com/json/...';
constructor(private http: Http) { }
getPage(): Observable<Page> {
return this.http.get(this.urlPage).map(this.extractData).catch(this.handleError);
}
private extractData(res: Response) {
let body = res.json();
return body || {};
}
private handleError(error: any) {
let errMsg = (error.message) ? error.message :
error.status ? `${error.status} - ${error.statusText}` : 'Server error';
console.error(errMsg);
return Observable.throw(errMsg);
}
}
This is my component:
import { Component, OnInit } from '@angular/core';
import { ProductService } from './product/productService';
import { Page } from './product/page';
@Component({
templateUrl: 'app/app.product.html',
selector: 'product-app',
providers: [ProductService]
})
export class AppProduct implements OnInit {
private errorMessage: string;
page: any;
constructor(
private productService: ProductService) {
}
ngOnInit() {
this.getPage();
}
getPage() {
this.productService.getPage().subscribe(
page => this.page = page,
error => this.errorMessage = <any>error
)
}
}