shark
shark

Reputation: 83

Angular Proxy timeout when trying to reach extrenal api

I have configured an Angular application to work with an Angular proxy. The Angular proxy is working fine when I'm redirecting API calls to local. But, when trying to connect to an external API, I'm getting a timeout.

I'm behind an enterprise proxy. I have set up my NPM proxy configuration to point to that proxy, but I'm still getting an error.

proxy.json config:

{
  "/api": {
    "target": "https://demo.zhaidongxi.com/yii2-app-example-backend-api",
    "secure": false,
    "changeOrigin": true,
    "pathRewrite": {
      "^/api": ""
    },
    "logLevel": "debug"
  }
}

The error I'm getting:

[HPM] Rewriting path from "/api/v1/login" to "/v1/login"
[HPM] POST /api/v1/login ~> https://demo.zhaidongxi.com/yii2-app-example-backend-api
[HPM] Error occurred while trying to proxy request /v1/login from localhost:4200 to https://demo.zhaidongxi.com/yii2-app-example-backend-api (ETIMEDOUT) (https://nodejs.org/api/errors.html#errors_common_system_errors)

Upvotes: 4

Views: 2905

Answers (1)

shark
shark

Reputation: 83

I figured out that i missed a part of the documentation. However, when being behind a corporate proxy the configuration has to be like that

If you work behind a corporate proxy, the backend cannot directly proxy calls to any URL outside your local network. In this case, you can configure the backend proxy to redirect calls through your corporate proxy using an agent

npm install --save-dev https-proxy-agent

When you define an environment variable http_proxy or HTTP_PROXY, an agent is automatically added to pass calls through your corporate proxy when running npm start.

Use the following content in the JavaScript configuration file.

    var HttpsProxyAgent = require('https-proxy-agent');
    var proxyConfig = [{
      context: '/api',
      target: 'http://your-remote-server.com:3000',
      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);

Source

Upvotes: 3

Related Questions