2017-01-03 124 views
1

創建一個MEAN堆棧應用程序,我有一個角度組件,在頁面加載時向亞馬遜產品API發出請求。我正在本地運行和測試本地主機(節點/快遞後端)。角度CORS與亞馬遜產品API

這裏是我的組件的基本要求代碼:

getAmazonTackle(amz:amazonservice) { 
var req:Object = { 
    method: this.amazonservice.Method, 
    url: this.amazonservice.Endpoint, 
    headers: { 
    //"Access-Control-Allow-Origin":"*" 
    }, 
    data: this.amazonservice.Data, 
    withCredentials: false 
} 
console.log(JSON.parse(JSON.stringify(req))); 
this.$http(req).then(
    function(response) { 
    console.dir('The response: '+response); 
    }, 
    function(response) { 
    console.dir(response); 
    console.dir('The error:'+response); 
    } 
) 

}

當我沒有Access-Control-Allow-Origin頭,訪問我呈現在下面的瀏覽器頁面Chrome的開發者控制檯:

XMLHttpRequest cannot load http://webservices.amazon.com/onca/xml?. 
No 'Access-Control-Allow-Origin' header is present on the requested resource. 
Origin 'http://localhost:3000' is therefore not allowed access. 

當我添加了Access-Control-Allow-Origin頭,我收到以下內容:

Response to preflight request doesn't pass access control check: 
No 'Access-Control-Allow-Origin' header is present on the requested resource. 
Origin 'http://localhost:3000' is therefore not allowed access. 

我想確定的是,如果我這樣做不正確,或者如果亞馬遜API不支持CORS。

回答

0

我面臨類似的問題,發現如果我創建cors啓用http處理程序,將作爲您的服務器和亞馬遜服務器之間的中間件。這樣我們可以解決這個問題。 這是很容易創建,我已經寫了它。

Develop Angular2 Application with real server APIs

退房的問題,並在上​​面的帖子答案。 類似的代碼我發佈在github上,如果需要我會分享位置。

注意:截至目前,我處理了獲取請求,但添加其他方法相當簡單。 https://github.com/Anil8753/CORSHttpHandler