2017-06-26 156 views
0

我有一个.wep API服务,它工作正常。当我想从Angularjs App.browser控制台获取数据时,给了我这个错误。Angular 2 Rest服务请求

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”标题。因此不允许访问原产地'http://localhost:4200'。 error_handler.js:54 EXCEPTION:状态响应:0表示URL:null

+0

我该如何在这里应用标题 –

回答

0

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

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

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

然后从你的代码中删除DNS全名是

this.http.get('/GetTweets') 

最后,运行你的应用程序作为如下:

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

你上4200上运行的服务器将重定向在URL中,关于6010运行在服务器/ GetTweets您的GET请求,你不会得到这个错误。

+0

非常感谢你的回答,对我来说工作正常 –