简体   繁体   English

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

[英]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.我有这个 MEAN Stack 应用程序,对于前端我使用的是 Angular 6,我创建了用户 root 和后端登录系统,我已经使用 Postman 对其进行了测试,它按预期工作。 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.我知道问题是将端口从4200更改为3000但还没有找到正确的解决方案。

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. 您必须在Angular ng serve设置代理,以向您的API发送请求。 Modify package.json to run ng serve with parameters: 修改package.json以使用参数运行ng serve

"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: 并创建proxy.config.json以将请求转发到后端,例如,假设您的后端运行在同一台机器和端口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. 我相信这可以在angular.json配置,但从未探索过该选项。

You can just use the full URL in your call like this 你可以像这样在你的通话中使用完整的URL

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 理想情况下,您应该在反向代理后面拥有微服务,并根据URI路径路由您的请求

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. 您可以尝试将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()));
  }

}

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. 这仍然可能会在请求时抛出CORS错误。 In order to prevent that add this code in your node application in app.js/index.js 为了防止在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 例如,您的evironment.dev.ts看起来像这样

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 要在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.

相关问题 从 android 设备向 PC 上的 nodejs 本地服务器发送 http 请求 - sending http requests from android device to nodejs local server on PC 如何在相同的端口 4200 上运行 angular 4 app 和 nodejs api 用于生产和开发? - how to run angular 4 app and nodejs api on same port 4200 for both production and development? 将数据从 angular 发送到在不同域上运行的 express nodejs 服务器 - Sending data from angular to express nodejs server running on different domain Angular Controller向Nodejs服务器发送数据或从Nodejs服务器接收数据 - Angular Controller Sending and Receiving Data to/from a Nodejs Server 通过Angular App和NodeJS向快递服务器发送GET / POST请求时如何修复404 Not Found - How to fix 404 Not Found when sending GET/POST requests to express server via Angular App and NodeJS 从Node.js服务器使用Gmail API发送邮件 - Sending mail using gmail api from nodejs server 将数据从 ReactJs(使用获取 API)发送到 nodeJs 服务器 - Sending data from ReactJs (using fetch API) to nodeJs server 文件未从 Angular 发送到 Nodejs - File not sending from Angular to Nodejs 将文件从 Angular 发送到 NodeJS - Sending file to NodeJS from Angular 将图像从 Nodejs 发送到 Angular - Sending image from Nodejs to Angular
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM