Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set the server port for sending API requests from Angular to NodeJS in development

I have this MEAN Stack application and for the front-end I'm using Angular 6, I created the users rooting and back-end login system and I've tested it using Postman and it works as expected. but when I use the form I always get this error below:

enter image description here

I know the problem is to change the port from 4200 to 3000 but haven't found the right solution.

here is my service:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { map } from 'rxjs/operators';

@Injectable()
export class UserService {

  constructor(
    private _httpClient: HttpClient
  ) { }


  public auth(user) {
    return this._httpClient.post('users/login', user).pipe(map((resp: any) => resp.json()));
  }

}

and this is where I use the service:

import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { UserService } from '../../services/user.service';



@Component({
  selector: 'app-side-menu',
  templateUrl: './side-menu.component.html',
  styleUrls: ['./side-menu.component.scss']
})
export class SideMenuComponent implements OnInit {

  public positionsList: Array<any> = [];
  public selectedOption: string;
  public feedbackMessage: string;

  public email: string;
  public password: string;

  public formNotValid: boolean;

  constructor(
    private _userService: UserService,
    private _router: Router
  ) { 

  }

  ngOnInit() {
  }

  public sendLoginForm() {
    if(!this.email || !this.password){
      this.formNotValid = true;
      this.feedbackMessage = "Both fields are required to login!";
      return false;
    }

    const user = {
      email: this.email,
      password: this.password
    }

    this._userService.auth(user).subscribe(resp => {
      if(!resp.success){
        this.feedbackMessage = resp.message;
        return false;
      }
    });
  }

  public getSelectedOption(option) {
    this.selectedOption = "as " + option;
  }


}

Any idea will be appreciated.

like image 774
Najm Eddine ZAGA Avatar asked Oct 26 '18 08:10

Najm Eddine ZAGA


2 Answers

You must setup proxy in Angular ng serve to foward requests to your API. Modify package.json to run ng serve with parameters:

"scripts": {
   .....
   "start": "ng serve --proxy-config proxy.config.json",
   .....
}

and create proxy.config.json to forward requests to your backend, for example, assuming your backend runs on the same machine and port 3000:

{
  "/api/*": {
   "target": "http://localhost:3000",
   "secure": false
  },
  "/__/*": {
    "target": "http://localhost:3100",
    "secure": false
  }
}

I believe this can be configured in angular.json as well however have never explored that option.

Edit: Here is how to set this up in angular.json (docs):

Open angular.json and find the key "serve"; then in the "options" below set the path to proxy config file in the "proxyConfig" key:

"serve": {
  "builder": "@angular-devkit/build-angular:dev-server",
  "configurations": {
     "production": {
        ...
     },
     "development": {
        ...
     }
  },
  "defaultConfiguration": "development",
  "options": {
     "proxyConfig": "proxy.config.json"
  }
}
like image 166
PeS Avatar answered Oct 26 '22 23:10

PeS


If you are working with different environments you can set up those in environment files

For example your evironment.dev.ts would look like this

export const environment = {
  production: false,
  API_REST_URL: 'https://yourDomainName', // can be http://localhost as well
  API_REST_PORT: 3000
};

And in your service you would use it like this

import { environment } from '/path/to/environment';

@Injectable()
export class MyService{
  apiPort = environment['API_REST_PORT'];
  apiUrl = environment['API_REST_URL'];

  constructor(private http: HttpClient) {
  }

  apiCall(): Observable<any> {
    return this.http.get(`${this.apiUrl}:${this.apiPort}/endpoint/path`)
      .pipe(map(data => {
        return data;
      }));
  }
}

And to serve your app in dev environment you can add your command to scripts object in package.json

 "scripts": {
    ...
    "start-dev": "ng serve --configuration=dev",
    "build:dev": "ng build --configuration=dev",
    ...
  },
like image 3
mxr7350 Avatar answered Oct 27 '22 01:10

mxr7350