gpt4 book ai didi

node.js - 在开发中设置从 Angular 向 NodeJS 发送 API 请求的服务器端口

转载 作者:可可西里 更新时间:2023-11-01 09:33:07 25 4
gpt4 key购买 nike

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

enter image description here

我知道问题是将端口从 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 中配置,但从未探索过该选项。

编辑:以下是如何在 angular.json ( docs ) 中进行设置:

打开angular.json,找到键"serve";然后在下面的 "options" 中,在 "proxyConfig" 键中设置代理配置文件的路径:

"serve": {
"builder": "@angular-devkit/build-angular:dev-server",
"configurations": {
"production": {
...
},
"development": {
...
}
},
"defaultConfiguration": "development",
"options": {
"proxyConfig": "proxy.config.json"
}
}

关于node.js - 在开发中设置从 Angular 向 NodeJS 发送 API 请求的服务器端口,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53004520/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com