簡體   English   中英

在開發中設置用於從Angular發送API請求到NodeJS的服務器端口

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

我有這個 MEAN Stack 應用程序,對於前端我使用的是 Angular 6,我創建了用戶 root 和后端登錄系統,我已經使用 Postman 對其進行了測試,它按預期工作。 但是當我使用表單時,我總是在下面收到此錯誤:

在此處輸入圖片說明

我知道問題是將端口從4200更改為3000但還沒有找到正確的解決方案。

這是我的服務:

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()));
  }

}

這是我使用該服務的地方:

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;
  }


}

任何想法將不勝感激。

您必須在Angular ng serve設置代理,以向您的API發送請求。 修改package.json以使用參數運行ng serve

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

並創建proxy.config.json以將請求轉發到后端,例如,假設您的后端運行在同一台機器和端口3000上:

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

我相信這可以在angular.json配置,但從未探索過該選項。

你可以像這樣在你的通話中使用完整的URL

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

理想情況下,您應該在反向代理后面擁有微服務,並根據URI路徑路由您的請求

您可以嘗試將api調用的url放在變量中,然后將其附加到具有特定路由的http動詞URL中。

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()));
  }

}

編輯您的服務文件:

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()));
  }

}

這仍然可能會在請求時拋出CORS錯誤。 為了防止在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();

});

如果您使用的是不同的環境,則可以在環境文件中設置它們

例如,您的evironment.dev.ts看起來像這樣

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

在你的服務中,你會像這樣使用它

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;
      }));
  }
}

要在dev環境中為您的應用程序提供服務,您可以將命令添加到package.json scripts object

 "scripts": {
    ...
    "start-dev": "ng serve --configuration=dev",
    "build:dev": "ng build --configuration=dev",
    ...
  },

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM