Stewart
Stewart

Reputation: 5022

How to serve a backend server which is local to the angular frontend?

I have an angular app running on an apache server at http://localhost.
I have a backend flask server running on the same machine on port 5200 (http://localhost:5200).

I can access the backend through the frontend from the server, but when I try from another machine, the front-end obviously refers the client to his own machine which isn't running the backend.

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { BehaviorSubject, Observable, of } from 'rxjs';

@Injectable()
export class DataService {    

  dataUrl = 'http://localhost:5002/api'

  constructor(private http: HttpClient) { }

  getData(): Observable<DataItem> {    
    return this.http.get<DataItem>(this.dataUrl)
  }
}

Is there a way for me to do something like this?

dataUrl = 'http://${SameIpAsFrontEnd}:5002/api'

Upvotes: 1

Views: 4725

Answers (2)

kedenk
kedenk

Reputation: 669

For these purposes, there are the environment files. You can use them to refer to different backend servers, which are in your case localhost and ´. You can use the standard development and prod environment file or you can create your own ones. If you useng serve` it will automatically run in dev mode, which will provide the dev environment file. But you can also provide an arbitrary file with (for example):

ng serve -e prod

Environment files are located in the directory environments. Suppose the file looks like this:

export const environment = {
    production: false,
    server: "localhost"
};

you can access the base URL with environment.server in your REST service for example. In the standard angular project, there will be environment.prod.ts and environment.ts. ng serve without -e will take environment.ts. If you use -e prod it will take the other one. Of course, you can also define an environment file like this: environment.stub.ts (ng serve -e stub).

In your example you can use:

dataUrl = 'http://' + environment.server + ':5002/api'

To build your application with a specific env file use:

ng build --prod --env=prod

Upvotes: 2

PR7
PR7

Reputation: 1914

This might help,

Try hosting site on first machine using command: ng serve --host 192.168.1.xx --port 80 Then enter the IP and port in the browser from another machine on same network: 192.168.1.xx:80

Upvotes: 0

Related Questions