cpc
cpc

Reputation: 638

Passing local node JS HTTP server port (running in electron) to angular service

I am running a RESTful node JS Http server on localhost within in my electron app. I listen on port 0, so that the OS gives me a random free port. How can I access the givin port within my angular code to be able to know on which URL I have to perform XHTTP requests?

restapi server (nodejs) running on 127.0.0.1:0

var listener = app.listen(port, server, function() {
        port = listener.address().port;
        console.log('Listening on port ' + port + '@' + server); 
    });

XHTTP call in angular

private heroesUrl = 'http://localhost:1337/api/heroes';

getHeroes(): Promise<Hero[]> {
    return this.http.get(this.heroesUrl).toPromise()
        .then(
            ((response) => response.json() as Hero[])
            )
        .catch(this.handleError);   
}

Any idea how I can replace the fixed port 1337 with the port that I get when opening the listener on the server side?

Or should I just use a fixed port on both sides and hope that it free? Sounds wrong to me.

Also I cant just go for '/api/heroes' as URL, because electron/angular is running on http://localhost:4200 (ng serve).

Upvotes: 1

Views: 2577

Answers (1)

Jack Clancy
Jack Clancy

Reputation: 1291

I typically use fixed ports when developing with this kind of set up, saves me the stress of worrying about configuring for dynamic ports. Also, depending on the way your Angular app is configured, you may need to set up a proxy. For example, below is how to implement the requested functionality if you are using angular-cli.

https://github.com/angular/angular-cli/blob/d22e9ae73763923980fc1e59cfb2a0bf255b98d8/docs/documentation/stories/proxy.md

Upvotes: 1

Related Questions