在 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,DocumentRoot
是 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);
});
}
文件结构:
最佳答案
您可以在 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/