代理Angular 7应用到在不同端口上运行的后端端点

时间:2019-04-11 19:17:09

标签: angular typescript proxy observable

我正在尝试设置一个后端代理,以便将在4200端口上运行的客户端应用程序上完成的所有请求都重写为80端口。

当我运行请求时:

  getTranslation(lang: string): Observable<any> {
    return this.http.get(`/translate?language=${lang}`)
    .pipe(map(response => response));
  }

应该点击localhost:80 / translate?language =“ zh-CN”,而是点击localhost:4200 / translate?language =“ zh-CN”。

我尝试通过angular.json添加proxy.conf.json进行设置:

"serve": {
  "builder": "@angular-devkit/build-angular:dev-server",
  "options": {
    "browserTarget": "client-app:build",
    "proxyConfig": "proxy.conf.json"
  },

看起来像这样:

{
  "/api": {
    "target": "http://localhost:80",
    "secure": false
  }
}

但这不起作用。我已经读过它在angular 7中做了一些不同,并且您通过ng serve传递了代理,如下所示:

"docker-start": "ng serve --host 0.0.0.0 --port 4200 --proxy-config proxy.js"

proxy.js文件为:

var HttpsProxyAgent = require('https-proxy-agent');
var proxyConfig = [{
  context: '/api',
  target: 'http://localhost:80',
  secure: false
}];

function setupForCorporateProxy(proxyConfig) {
  var proxyServer = process.env.http_proxy || process.env.HTTP_PROXY;
  if (proxyServer) {
    var agent = new HttpsProxyAgent(proxyServer);
    console.log('Using corporate proxy server: ' + proxyServer);
    proxyConfig.forEach(function(entry) {
      entry.agent = agent;
    });
  }
  return proxyConfig;
}

module.exports = setupForCorporateProxy(proxyConfig);

但是这似乎也不起作用,并且请求继续针对localhost:4200。

如果重要的话,该应用程序正在docker容器中运行。

想法?

1 个答案:

答案 0 :(得分:1)

您的代理配置中的上下文部分配置了受代理影响的路由,因此,代理不会干预您的角度应用程序中的实际路由。

您的代理配置指出,以/ api开头的所有内容都将重定向到端口80。因此,如果您的翻译请求为/ api / translate,则您的代理将生效。