Luki
Luki

Reputation: 419

How to read online html document to string in Angular

I am trying to read online html document and parse some data from it using Angular. The problem is I am keep getting an error about cors. My code for reading html document is:

  loadParsingData(htmlToParse:String){
     let retVal = this.http.get(htmlToParse.toString())
     .map(res => res.text())
     return retVal; }

When I try to test this code I expect to get html document from given website (for example imdb most popular movies) as argument, but all I get is:

XMLHttpRequest cannot load http://www.imdb.com/chart/moviemeter?ref_=nv_mv_mpm_8. No 'Access-Control-Allow-Origin' header is present on the requested resource.

Can anyone please help me? Thank you in beforehand.

Upvotes: 0

Views: 188

Answers (1)

sideshowbarker
sideshowbarker

Reputation: 88005

You can send your request through a CORS proxy instead.

Where you’re specifying the URL http://www.imdb.com/chart/moviemeter?ref_=nv_mv_mpm_8 in your code now, just replace that with this URL:

https://cors-anywhere.herokuapp.com/http://www.imdb.com/chart/moviemeter?ref_=nv_mv_mpm_8

That will cause the request to be sent to https://cors-anywhere.herokuapp.com, a proxy that will then send the request on to http://www.imdb.com/chart/moviemeter?ref_=nv_mv_mpm_8. And when that proxy gets the response, it will take it and add the Access-Control-Allow-Origin response header to it and then pass that back to your requesting frontend code as the response.

That response with the Access-Control-Allow-Origin response header is what your browser sees, so the error message the browser is showing you now goes away, and the browser allows your frontend JavaScript code to access the response.

https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS has general details on CORS, and "No 'Access-Control-Allow-Origin' header is present on the requested resource" is an answer with more details about how you can set up your own CORS proxy.

Upvotes: 1

Related Questions