当我使用 ng build 时,proxy.config.json 在 Angular 4/5 中不起作用

Aru*_*rul 6 build angular

我正在使用代理 api 设置来进行 angular 5 中的 API 调用,如本网站所述。https://juristr.com/blog/2016/11/configure-proxy-api-angular-cli/ 当我使用 npm start 时,这可以正常工作。但是当我构建它并将其托管在 IIS 上时。它不工作。我相信 proxy.config.json 没有添加到 dist 文件夹中。

小智 11

我和你面临同样的问题。我的 proxy.config.json 已在我的开发环境中工作,但即使我使用 build --prod 构建,也无法在 PROD 环境中工作

找到方法后,我找到了一个用中间件代替代理后端的解决方案(在我的例子中我使用了 Nginx)。

如果您还使用了 Nginx,您可以通过将其配置到您的 nginx 配置中来做代理后端。

配置文件

location /api/ {
  proxy_pass      http://127.0.0.1:8087; 
  #all incoming http request with /api/ will be forwarded to http://127.0.0.1:8087/api/
}
Run Code Online (Sandbox Code Playgroud)


Mix*_*off 5

当开发服务器处于活动状态时,代理正在工作。ng build不启动开发服务器,此命令仅构建项目。因此,您不能在组装的项目中使用代理。您可以使用类似的方法在带有代理的环境ng serve --proxy-config proxy.config.json --prod中进行测试prod

如果您需要在生产中使用另一个基本 url,您可以使用HttpInterceptor. 只需创建这样的服务

@Injectable()
export class InterceptorsService implements HttpInterceptor {

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
      const proxyReq = req.clone({ url: `${ BASE_PATH }${ request.url }` });
      return next.handle(proxyReq);
    }
}
Run Code Online (Sandbox Code Playgroud)

并将其添加到模块中的提供者中

...
providers: [
    { provide: HTTP_INTERCEPTORS, useClass: InterceptorsService, multi: true }, ...
]
...
Run Code Online (Sandbox Code Playgroud)