angular - 在 Angular 应用程序中代理时出现 504(网关超时)错误

标签 angular

我正在尝试设置 Angular 应用程序以使用 2 个不同的本地主机。

我在项目根目录下创建了一个 backend 文件夹,并在其中添加了 echo.php 文件。在项目根目录中,我还使用以下内容创建了 proxy.conf.json:

{
  "/backend/**": {
    "target": "http://localhost:80",
    "secure": false

  }
}

我尝试使用以下方法获取 echo.php:

  ngOnInit(){
    this.http.get('http://localhost:4200/backend/echo.php').subscribe(data => {
      console.log(data);      
    });
  }

启动 Angular 应用程序:

ng serve --port 4200 --host 0.0.0.0 --proxy-config proxy.conf.json

在浏览器控制台中,我收到 504 错误网关超时。在终端中,错误听起来有点不同:

[HPM] Error occurred while trying to proxy request /backend/echo.php from localhost:4200 to http://localhost:80 (ENOTFOUND)

我不知道我做错了什么。你能为我指出正确的方向吗? 我可以直接使用此 url 访问非 Angular (在端口 80 上运行)服务器上的文件:http://localhost/backend/echo.php .

编辑:

回声.php:

<?php
echo "data from php";

最佳答案

很多很多小时后,我发现了真正的问题。它源于在 proxy.conf.json 中指定目标。这是正确的:

{
  "/backend/*": {
    "target": "http://127.0.0.1",
    "secure": false,
    "changeOrigin":true,
    "logLevel": "debug"
  }
}

这不是:

{
  "/backend/*": {
    "target": "http://localhost",
    "secure": false,
    "changeOrigin":true,
    "logLevel": "debug"
  }
}

这可能与无法自行执行 ng serve 有关。

ng serve 

命令返回错误:

getaddrinfo ENOTFOUND localhost
Error: getaddrinfo ENOTFOUND localhost
    at errnoException (dns.js:28:10)
    at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:76:26)

这是一个老问题,我从来没有弄清楚这个错误的根源。相反,我只是使用 ng serve --port 4200 --host 0.0.0.0 来绕过它。

如果有人能解释为什么会这样,那就太棒了。我的 /etc/hosts 文件包含以下内容:

127.0.0.1       localhost
255.255.255.255 broadcasthost
::1             localhost
192.168.1.1      router.hm
127.0.0.1 My-MBP # added by Apache Friends XAMPP

关于angular - 在 Angular 应用程序中代理时出现 504(网关超时)错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47612074/

相关文章:

angular - 如何在组件中传递具有泛型类型 T 的 @input() 属性 ( @Input() ItemList : T[] = [];)

angular - 命名空间 'firebase' 没有导出成员 'firestore'

typescript - 如何为 plunker 创建 Angular2 单个文件?

Angular mat-selection-list,如何使单个复选框选择类似于单选按钮?

angular - 用 jest 测试 Angular 组件给出了resolveComponentResources

javascript - 错误 : Metadata version mismatch for module ngx-swiper-wrapper found version 4, 中的错误预期 3

angular - 汇总和 Redux : "index.js does not export default"

java - 如何将后端传入的数据存储到周期元素类型的数组对象中

javascript - 编译后将基本赋值写入 if 语句

angular - 从 Angular 2 中的 Hal+JSON 对象解析信息