angular - 在 Angular 中从不同的本地主机获取数据

标签 angular

在 Angular 中,ng serve --port 4200 --host 0.0.0.0 创建了一个 http 服务器实例。有人告诉我,为了从 Angular 中的服务器端脚本获取数据,需要另一个本地主机。

在 ngOnInit 中我获取数据:

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

此提取在 Developer tools 的 Network 选项卡 中有一个状态代码 200 但我在控制台中收到 CORS 错误:

Failed to load http://localhost/echo.php: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access.

这似乎是不同的端口导致的。我应该怎么做才能防止这种情况发生?浏览器本身通过获取此文件没有问题,是 Angular 提示。

更新:我听从了建议并提出了一个新错误。这次是:GET http://localhost:4200/backend/echo.php 504 (Gateway Timeout)

“其他”服务器配置为监听端口 80,DocumentRootbackend ..

proxy.conf.json:

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

.ts:

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

文件结构:

enter image description here

最佳答案

您可以在 http://localhost 上代理您的应用程序通过在您的 Angular 项目中创建一个名为 proxy.conf.json 的文件,其中包含以下内容:

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

然后使用附加参数 --proxy-config proxy.conf.json 启动 ng serve

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

你必须改变你的电话,然后包括端口和 /api 前缀:

this.http.get('http://localhost:4200/api/echo.php').subscribe(data => {
...

您可以找到更多详细信息 here

关于angular - 在 Angular 中从不同的本地主机获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47608247/

相关文章:

javascript - 跳过 NULL 并在下拉列表中仅显示唯一值

javascript - Angular:导出类和公共(public)类之间的区别?

javascript - 核心模块是否应该在 Angular2 中导入共享模块

angular - NGRX 影响如何将参数传递给 withLatestFrom 操作符

angular - 类型错误 : Invalid Event Target - But just by using direct Route

angular - 尝试在 Android 上运行 ionic 时找不到模块 '@angular-devkit.../utils'

angular - 垫自动完成多个字段

angular - 使用 angular2-logger 的 Angular 5 项目中的错误

angular - 在非 ionic (Angular 6)应用程序中使用不带 unpkg cdn 的 @ionic/core

angular - 我需要在 CI 作业中缓存什么以避免每次 ngcc 重新编译?