【问题标题】:Angular 2 Rest service request [duplicate]Angular 2 Rest服务请求[重复]
【发布时间】:2017-11-29 14:19:23
【问题描述】:

我有一个运行良好的.net Wep API 服务。当我想从 Angularjs 获取数据时,App.browser 控制台给了我这个错误。

getCurrentFeed() :Observable<Tweet[]>{

  return this.http.get('http://localhost:6010/GetTweets').map((resp :Response)=>{
    console.log(resp.json());
    var fetchedTweets=[];
    for(let tweet of resp.json().data)
    {
     fetchedTweets.push(this.getTweetFromJson(tweet));

    }
    return fetchedTweets as Array<Tweet>;
});

}

XMLHttpRequest 无法加载 http://localhost:6010/GetTweets。请求的资源上不存在“Access-Control-Allow-Origin”标头。因此,Origin 'http://localhost:4200' 不允许访问。 error_handler.js:54 例外:响应状态:0 对于 URL:null

【问题讨论】:

  • 我如何在这里应用标题

标签: angular rest angular2-services


【解决方案1】:

由于您的客户端应用程序由在端口 4200 上运行的开发服务器提供服务,因此客户端不允许访问其他服务器,除非它们专门配置为允许访问您的客户端。

在开发模式下,您不必配置服务器的标头。只需在客户端上配置一个简单的代理。在项目的根目录中创建一个文件 proxy-conf.json,内容如下:

{
  "/GetTweets": {
    "target": "http://localhost:6010",
    "secure": false
  }
} 

然后从您的代码中删除完整的 DNS 名称

this.http.get('/GetTweets') 

最后,按如下方式运行您的应用:

ng serve --proxy-config proxy-conf.json

您在 4200 上运行的服务器会将 URL 中包含 /GetTweets 的 get 请求重定向到在 6010 上运行的服务器,您不会收到此错误。

【讨论】:

  • 非常感谢您的回答,它对我来说很好
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-16
  • 2020-04-23
  • 1970-01-01
  • 2023-04-07
  • 2014-11-18
  • 2015-04-19
相关资源
最近更新 更多