简体   繁体   中英

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:

在此处输入图片说明

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.

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.

You can just use the full URL in your call like this

this._httpClient.post(window.location.protocol + '//' + window.location.hostname + ':3000/' + 'users/login', user)

Ideally, you should have you microservices behind a reverse proxy and route your requests based on URI paths

You may try putting the url for the api calls in a variable and then appending it in the http verbs url with the specific route.

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

@Injectable()
export class UserService {
url='http://localhost:3000/'
  constructor(
    private _httpClient: HttpClient
  ) { }


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

}

Edit your service file:

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('http://localhost:3000/users/login', user).pipe(map((resp: any) => resp.json()));
  }

}

This still may throw CORS error upon request. In order to prevent that add this code in your node application in app.js/index.js

app.use((req , res , next) => {

    res.header("Access-Control-Allow-Origin" , "*");
    res.header(
        "Access-Control-Allow-Headers" ,
        "Origin, X-Requested-With, Content-Type, Accept, Authorization"
    );
    next();

});

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",
    ...
  },

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM