2016-08-09 48 views
1

我見過this,我有一些問題。Angular2:沒有'Access-Control-Allow-Origin'標頭出現在請求的資源上。原因'空'因此是不允許訪問

我想從這個URI的響應:

http://www.instagram.com/justinbieber/media/ 

,我已經實現了下面的代碼吧:

import {Http,Headers} from '@angular/http'; 
import {Observable} from 'rxjs/Observable'; 
import 'rxjs/add/operator/map'; 
import {Component,Injectable} from '@angular/core'; 
import {Gallery} from './gallery';  

@Injectable() 
export class InstagramService{ 

    constructor(private _http:Http){    

    } 

    getGallery(username: string) : Observable<Gallery> { 

     return this._http.get("http://www.instagram.com/justinbieber/media/").map(res => res.json());                    
    } 
} 

Unfortunatlly,當我把這種服務也抱怨有:

XMLHttpRequest cannot load https://www.instagram.com/justinbieber/media/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. 

所以有一些問題對我來說:

1-我可以從我的瀏覽器或甚至postman得到響應,但不在我的代碼中。是什麼導致這個問題?

2-在這種情況下,我的代碼有問題,請提供您的建議?

提示:本uri不支持jsonp.get

回答

1

您應該使用支持JSONP的Instagram API。下面是一個示例:

constructor(private jsonp:Jsonp) { 
    let url = 'https://api.instagram.com/v1/tags/ootd/media/recent?client_id=someidnumbersxxxxxxxxxxxxxx&callback=JSONP_CALLBACK'; 
    jsonp.request(url, { method: 'Get' }) 
     .subscribe((res) => { 
     (...) 
     }); 
} 

看到這些問題的更多詳細信息:

+1

的問題是,它不是在你的應用程序Angular2一個問題。對於Postman來說,事情有點不同,因爲它是一個Chrome插件,所以對HTTP調用的限制是不一樣的。爲了解決您收到的錯誤,必須在服務器端完成一些事情,這取決於Instagram。 JSONP支持同樣的東西。這就是爲什麼我處理支持JSONP的Instagram API。希望它能回答你的問題;-) –

+1

也許這篇文章可能會讓你感興趣:http://restlet.com/blog/2015/12/15/understanding-and-using-cors/。 –

+0

本文也是如此:http://restlet.com/blog/2016/09/27/how-to-fix-cors-problems/ –

相關問題