2017-06-26 155 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

非常感謝你的回答,對我來說工作正常 –