[英]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.