Marcel Jacques Machado Marcel Jacques Machado - 4 years ago 235
TypeScript Question

How to solve "Access-Control-Allow-Origin" issue in Angular2 + Lite-Server?

I have an Angular 2 application that requests data from an external API.

I can't change the API code, but I'm able to change the TypeScripts and the Lite-Server configuration.

Error:
XMLHttpRequest cannot load http://api.zanox.com/.... No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4000' is therefore not allowed access.

I already saw a lot of content about CORS but I don't know how to adapt that to my code. What's the easiest way to solve that?

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);
}

}


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
)
}
}

Answer Source

I could solve the issue using JSONP:

app.module.ts:

import { JsonpModule } from '@angular/http';

@NgModule({
    imports: [JsonpModule]
})

productService.ts:

import {Jsonp} from '@angular/http';

private urlPage = 'http://api.zanox.com/json/...&callback=JSONP_CALLBACK';

constructor(private _jsonp: Jsonp) {}

getPage(): Observable<Page> {
    return this._jsonp.get(this.urlPage).map(this.extractData).catch(this.handleError);
}

Thanks, God!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download