1

Im new in Angular 2 framework and I try tu understand Http object. Im following the tutorial here:

http://www.joshmorony.com/using-http-to-fetch-remote-data-from-a-server-in-ionic-2/

Its perfect to retrieve JSON file from a server that provide this kind of data but I want to retrieve the HTML content into a variable. I would like to have all the html file and parse it to get some informations.

When I modify the URL in the example by a website like this:

this.http.request('https://www.google.ca/' ).map(res => res.text()).subscribe(data => {
    this.webPage = data.toString();
    console.log("data:" + data );
});

I got this error:

EXCEPTION: Response with status: 0 for URL: null

Do I use the good API? What im doing wrong?

Thanks, Pat

1 Answer 1

1

This is a CORS problem.
The full error is:

XMLHttpRequest cannot load https://www.google.ca/. 
No 'Access-Control-Allow-Origin' header is present on the requested resource.
Origin 'https://run.plnkr.co' is therefore not allowed access.  
EXCEPTION: Response with status: 0  for URL: null

You cannot request 'https://www.google.ca/' because: 1) when you make a http request in your app, the origin is already defined as your host, could be 'localhost' or your site's host. 2) 'www.google.ca' is another origin, and it has no 'Access-Control-Allow-Origin' set, or you site's host is not in their 'Access-Control-Allow-Origin' list.

If you want the html of 'www.google.ca', you need a proxy server, and the steps are: 1) in your ng2 app, you send a request to proxy server and ask it to do ... 2) you proxy server request 'www.google.ca' and send the html to your ng2 app.

When the proxy server request 'www.google.ca', the origin is defined as 'www.google.ca'. So the proxy server can get the html.

Sign up to request clarification or add additional context in comments.

3 Comments

So if I understand, on my application I cant do what I want. I need to setup an server on a computer to do the proxy. Alright, it's more complex than what I was thinking. Thanks!
On Ionic, do you know if there is a plugin to do the server job?
I've not used ionic and have no idea about its plugins. But after searchig 'ionic cors', I got this article, may you find something useful after line 'The Ionic CLI proxy server'.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.