我是Angular发展的新手。这是我的代码:
export class FaceProfilComponent implements OnInit {
domparser = new DOMParser();
doc: HTMLDocument;
element: any;
constructor(private http: HttpClient) {}
getID() {
url = 'https://www.facebook.com/zuck';
this.http.get(url, {withCredentials: true, responseType: 'text'}).subscribe(data => {
this.doc = this.domparser.parseFromString(data, 'text/html');
this.element = this.doc.getElementsByTagName('meta')[5].content;
console.log(this.element);
});
}
}
我希望得到fb://profile/4
的回复,但结果总是Failed to load https://www.facebook.com/zuck: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access.
我不知道该怎么办。
我正在使用Angular 5 cli。我经常阅读https://enable-cors.org/server_expressjs.html
,但我不明白如何做正确的事情,因为我使用Webpack。
答案 0 :(得分:0)
首先,这与Angular本身无关。你会以任何其他方式发出同样的错误。
您从Facebook获得的响应没有CORS标头,因此出于安全原因,您的客户拒绝这些数据,因为它来自与您用于提供Angular内容的任何域不同的域。
需要在从中获取数据的服务器上启用CORS,因此您无法在Facebook上执行此操作。您可以放置一个代理服务器,在其间添加此标头,然后将请求发送到代理。例如: https://www.npmjs.com/package/cors-anywhere
如果仅用于本地测试,您还可以在浏览器中禁用CORS(存在安全风险)。