Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Configure port for HTTP in Angular.io

Tags:

angular

I want to create an angular.io application, but the rest API shall be delivered from a different server port.

Angular content from localhost:4200, the data from a node express server started independently on localhost:3000. But when I inject and use 'http', how can I configure the port to be used?

like image 986
fbenoit Avatar asked Feb 07 '17 21:02

fbenoit


People also ask

What is HTTP protocol in angular?

Angular provides a client HTTP API for Angular applications, the HttpClient service class in @angular/common/http . The HTTP client service offers the following major features. The ability to request typed response objects. Streamlined error handling. Testability features.


2 Answers

Solutions with somehow getting the "right" URL did not work.
It turned out that this leads to a situation, where a http.put(...) was seen on the rest server as an OPTIONS request.

Angular $http is sending OPTIONS instead of PUT/POST

I found a working way, by proxying from the angular server to the rest server:

angular-cli server - how to proxy API requests to another server?

ng serve --proxy-config proxy.conf.json

the proxy.conf.json:

{
   "/api": {
      "target": "http://localhost:3000",
      "secure": false
   }
}
like image 183
fbenoit Avatar answered Nov 04 '22 06:11

fbenoit


Assuming that you're using the Angular CLI to scaffold your project (I hope that you are), you should already have access to different environment settings. These files allow you to easily provide values to your application that can vary depending on where it's running.

environment.ts provides the interface for your environment values and then environment.qa.ts, environment.prod.ts, etc (you can create as many environments as you want) allow you to specify different values that correspond to that environment.

Assuming that you have something like this in your environment file:

export const environment = {
    myEndpoint: 'localhost:3000'
}

You can run or build the app using the --env flag to get the appropriate values:

ng build --env=qa

Accessing the values defined in your env config are easy. In your service or component just add an import for environment:

import { environment } from '../../environments/environment';

And then use the value:

this.http.get(environment.myEndpoint)
like image 23
Jesse Carter Avatar answered Nov 04 '22 08:11

Jesse Carter