【问题标题】:Angular app on Apache server cannot find backendApache 服务器上的 Angular 应用程序找不到后端
【发布时间】:2019-06-11 00:44:36
【问题描述】:

我有一个 Angular 6 应用程序,我以 npm start 开头,并带有用于后端配置的 proxy.conf.json 配置:

{
  "/api/*": {
    "target": "http://123.123.1.23:8080",
    "secure": false,
    "logLevel": "debug",
    "changeOrigin": true
  }
}

应用程序工作正常,但是当我使用ng build(不带 -prod)编译它并将其部署在 /var/www/html 下的 Apache 服务器上时,我可以打开网页,但与后端的通信可能无法正常工作因为无法被发现。

我在/etc/apache2/sites-enabled/000-default.conf中添加了这个apache配置

<Directory "/var/www/html">
  AllowOverride All
</Directory>

但我仍然无法登录。你知道我在配置中遗漏了什么吗?

【问题讨论】:

  • 据我所知,代理仅用于开发时间。它从来都不是用于生产的。
  • 好的,我应该使用什么配置?
  • IMO,最好是做http拦截器。
  • 你能给我举个例子吗?

标签: angular apache apache2


【解决方案1】:

我的一个项目中的 Http 拦截器示例:

其中 apiUrl 是您的 API url 在 environment.ts 文件中定义的位置。

@Injectable()
export class HttpRequestInterceptorService implements HttpInterceptor {

  constructor() {}

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    const url = environment.apiUrl;

    req = req.clone({
      url: url + req.url,
      headers: new HttpHeaders({
        'Cache-Control': 'no-cache',
        'Pragma': 'no-cache',
        'Expires': 'Sat, 01 Jan 2000 00:00:00 GMT'
      })
    });

    return next.handle(req)
      .pipe(catchError(error => {
        if ((<HttpErrorResponse>error).status === 401) {
          console.log(error);
        }
        return throwError(error);
      }));
    }
  }

注册模块:

@NgModule({
  declarations: [],
  imports: [
    CommonModule,
    HttpClientModule
  ],
  providers: [
  ]
})
export class WebRequestInterceptorModule {
  constructor(@Optional() @SkipSelf() parentModule: WebRequestInterceptorModule) {
    if (parentModule) {
      throw new Error('WebRequestInterceptorModule is already loaded. Import it in AppModule only');
    }
  }

  static forRoot(): ModuleWithProviders {
    return {
      ngModule: WebRequestInterceptorModule,
      providers: [
        {provide: HTTP_INTERCEPTORS, useClass: HttpRequestInterceptorService, multi: true}
      ]
    };
  }
}

然后在你的 app.module.ts 上注册它 WebRequestInterceptorModule.forRoot()

【讨论】:

  • 您能否将答案扩展一点,我应该在哪个文件和位置添加这些配置?
猜你喜欢
  • 1970-01-01
  • 2018-08-16
  • 1970-01-01
  • 2020-06-24
  • 1970-01-01
  • 2020-12-19
  • 2019-01-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多