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

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

问题描述:

我正在使用代理API设置来按角度5进行API调用,如本网站所述."> 当我使用npm start时,此工作正常.但是当我构建它并将其托管在IIS上时.它不起作用.我相信proxy.config.json不会添加到dist文件夹中.

i am using proxy api setting for API calls in angular 5 as discussed in this website .https://juristr.com/blog/2016/11/configure-proxy-api-angular-cli/ this working properly when i use npm start. but when i build this and host it on IIS. it is not working. i believe proxy.config.json is not added inside dist folder.

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

Proxy is working when dev server active. ng build doesn't start dev server, this command only build the project. Therefore you cannot use proxy in assembled project. You can use smth like ng serve --proxy-config proxy.config.json --prod for testing in prod environment with proxy

如果需要在生产中使用其他基本URL,则可以使用HttpInterceptor.只需创建这样的服务

If you need to use another base url in production, you can use HttpInterceptor. Just create service like this

@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);
    }
}

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

and add it to providers in your module

...
providers: [
    { provide: HTTP_INTERCEPTORS, useClass: InterceptorsService, multi: true }, ...
]
...