在开发中设置用于从Angular发送API请求到NodeJS的服务器端口

Naj*_*AGA 5 mongodb node.js express angular

我有这个 MEAN Stack 应用程序,对于前端我使用的是 Angular 6,我创建了用户 root 和后端登录系统,我已经使用 Postman 对其进行了测试,它按预期工作。但是当我使用表单时,我总是在下面收到此错误:

在此处输入图片说明

我知道问题是将端口从 更改为42003000但还没有找到正确的解决方案。

这是我的服务:

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

}
Run Code Online (Sandbox Code Playgroud)

这是我使用该服务的地方:

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


}
Run Code Online (Sandbox Code Playgroud)

任何想法将不胜感激。

PeS*_*PeS 6

您必须在 Angular 中设置代理ng serve才能将请求转发到您的 API。修改package.jsonng serve带参数运行:

"scripts": {
   .....
   "start": "ng serve --proxy-config proxy.config.json",
   .....
}
Run Code Online (Sandbox Code Playgroud)

并创建proxy.config.json将请求转发到您的后端,例如,假设您的后端运行在同一台机器和端口 3000 上:

{
  "/api/*": {
   "target": "http://localhost:3000",
   "secure": false
  },
  "/__/*": {
    "target": "http://localhost:3100",
    "secure": false
  }
}
Run Code Online (Sandbox Code Playgroud)

我相信这也可以配置,angular.json但从未探索过该选项。


Pra*_*ala 0

您可以像这样在调用中使用完整的 URL

this._httpClient.post(window.location.protocol + '//' + window.location.hostname + ':3000/' + 'users/login', user)
Run Code Online (Sandbox Code Playgroud)

理想情况下,您应该将微服务置于反向代理后面,并根据 URI 路径路由您的请求