当我使用ng build时proxy.config.json在Angular 4/5中不起作用 [英] proxy.config.json is not working in Angular 4/5 when i use ng build

查看:304
本文介绍了当我使用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 }, ...
]
...

这篇关于当我使用ng build时proxy.config.json在Angular 4/5中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆