Reputation: 129
this is my first post so please let me know if I need to add any screenshots or code snippets.
I recently created a new app using the Angular 2 CLI. I'm able to load data via mocks but I am struggling with how to connect to end API's while still using the dev server provided by the CLI for "live" testing of changes.
I currently have the standard CLI port of 4200, and an express backend at 8181.
While following the angular docs for get calls I'm running into an issues since my API calls are to the 8181 port, with browser console error:
No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access.
note - checked Angular 2 cli with Express js but doesn't seem to address my exact problem / question
What is the proper way to take advantage of the development server while connecting to an express server as for API's? Thanks so much in advance!
service:
import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/toPromise';
import { Sport } from './sport';
@Injectable()
export class SportService {
private sportsUrl = 'http://localhost:8181/sports'; //URL to web API
constructor(private http: Http) { }
getSports(): Promise<Sport[]> {
return this.http.get(this.sportsUrl)
.toPromise()
.then(response => response.json().data as Sport[])
.catch(this.handleError);}
private handleError(error: any): Promise<any> {
console.error('An error occurred', error); // for demo purposes only
return Promise.reject(error.message || error);
}
}
component:
import { Component } from '@angular/core';
import { OnInit } from '@angular/core';
import { Sport } from './sport';
import { SportService } from './sport.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
providers: [SportService]})
export class AppComponent implements OnInit {
ngOnInit(): void {
this.getSports();}
title = 'Olympics';
constructor(private sportService: SportService) { }
sports: Sport[];
getSports(): void {
this.sportService.getSports().then(sports => this.sports = sports);
}
}
Upvotes: 1
Views: 226
Reputation: 12376
You need to configure a proxy. Create a file proxy-conf.json with the following content (assuming that the endpoints in your express server contain /api
):
{
"/api": {
"target": "http://localhost:8181",
"secure": false
}
}
Start your Angular CLI app as follows:
ng serve --proxy-config proxy.conf.json
Upvotes: 1