Angular代理在尝试访问外部API时超时

4
我已经配置了一个与Angular代理一起使用的Angular应用程序。当我将API调用重定向到本地时,Angular代理正常工作。但是,当尝试连接到外部API时,我会遇到超时错误。
我在企业代理后面。我已经设置了我的NPM代理配置以指向该代理,但仍然出现错误。 proxy.json配置:
{
  "/api": {
    "target": "https://demo.zhaidongxi.com/yii2-app-example-backend-api",
    "secure": false,
    "changeOrigin": true,
    "pathRewrite": {
      "^/api": ""
    },
    "logLevel": "debug"
  }
}

我收到的错误消息:
[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)
1个回答

3

我发现我错过了文档的一部分。 然而,当你在公司代理后面时,配置必须是这样的:

如果你在公司代理后面工作,后端无法直接代理到你本地网络以外的任何URL。在这种情况下,你可以使用代理来配置后端代理,通过公司代理重定向调用。

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

当您定义环境变量http_proxy或HTTP_PROXY时,在运行npm start时会自动添加代理以通过公司代理传递调用。
请在JavaScript配置文件中使用以下内容。
    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


仅提供链接的答案不受好评,也不会长久存在。您能否考虑将链接中相关部分并入答案中? - theMayer

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接