在角度中,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);
});
}
此获取有一个状态代码200
in Network tab of Developer tools
但我在控制台中收到 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)
“其他”服务器配置为侦听端口 80DocumentRoot
being backend ..
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);
});
}
文件结构: