从Angular中的其他本地主机获取数据 [英] fetch data from different localhost in Angular

查看:112
本文介绍了从Angular中的其他本地主机获取数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

in Angular, ng serve --port 4200 --host 0.0.0.0 creates an instance of http server. I've been told, that in order to fetch data from server side scripts in Angular, another localhost is needed.

在ngOnInit中,我获取数据:

In ngOnInit I fetch the data:

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

此抓取在Network tab of Developer tools中的状态码为200,但在控制台中出现了CORS错误:

This fetch has a status code 200 in Network tab of Developer tools but I am getting a CORS error in the console:

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.

It appears that differenr ports cause this. What should I do to prevent that? Browser itself has no issue by fetching this file, it is Angular that complains.

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

UPDATE: I've followed the suggestions and came up with a new error. this time it is: GET http://localhost:4200/backend/echo.php 504 (Gateway Timeout)

其他"服务器配置为侦听端口80,而DocumentRootbackend ..

the "other" server is configured to listen to port 80 with DocumentRoot being backend ..

proxy.conf.json:

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);      
    });
  }

文件结构:

推荐答案

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

You can proxy your application on http://localhost by creating a file called proxy.conf.json in your angular project with the following content:

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

,然后从附加参数--proxy-config proxy.conf.json

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

您必须先更改呼叫,然后添加端口和/api前缀:

You have to change your call then to include the port and /api prefix:

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

您可以找到更多详细信息此处

You can find more details here

这篇关于从Angular中的其他本地主机获取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆