首页 > 解决方案 > 如何为角度前端本地的后端服务器提供服务?

问题描述

我有一个在 apache 服务器上运行的 Angular 应用程序http://localhost。我有一个后端烧瓶服务器在端口 5200 ( )
上的同一台机器上运行。http://localhost:5200

我可以从服务器通过前端访问后端,但是当我从另一台机器上尝试时,前端显然将客户端引用到他自己的没有运行后端的机器上。

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { BehaviorSubject, Observable, of } from 'rxjs';

@Injectable()
export class DataService {    

  dataUrl = 'http://localhost:5002/api'

  constructor(private http: HttpClient) { }

  getData(): Observable<DataItem> {    
    return this.http.get<DataItem>(this.dataUrl)
  }
}

有没有办法让我做这样的事情?

dataUrl = 'http://${SameIpAsFrontEnd}:5002/api'

标签: angular

解决方案


出于这些目的,有环境文件。您可以使用它们来引用不同的后端服务器,在您的情况下localhost,“ . You can use the standard development and prod environment file or you can create your own ones. If you useng serve”将自动在开发模式下运行,这将提供开发环境文件。但您也可以提供任意文件(例如):

ng serve -e prod

环境文件位于目录中environments。假设文件如下所示:

export const environment = {
    production: false,
    server: "localhost"
};

environment.server例如,您可以在 REST 服务中访问基本 URL 。在标准角度项目中,会有environment.prod.tsenvironment.tsng serve没有-e将采取environment.ts。如果您使用-e prod它,它将采取另一个。当然,您也可以像这样定义环境文件:( environment.stub.ts) ng serve -e stub

在您的示例中,您可以使用:

dataUrl = 'http://' + environment.server + ':5002/api'

要使用特定的 env 文件构建应用程序,请使用:

ng build --prod --env=prod

推荐阅读