Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Https request with XMLHttpRequest

Im able to do Http requests (POST/GET) with XMLHttpRequest.

I'm asking how to do requests with URLs like "https://www.gmail.com" I was trying something like this but the status code is 0

var http = new XMLHttpRequest();
    var url = "https://www.gmail.com";

    http.open("GET", url);
    http.onreadystatechange = function() {//Call a function when the state changes.
            if(http.readyState == 4 && http.status == 200) {
                    //alert(http.responseText);
                print("ok")
            }else{
                print("cannot connect")
                print("code:" + http.status)
                print(http.responseText)
            }
    }
    http.send(null);

I get always "cannot connect" "code" 0 and nothing as response

Any idea?

like image 248
fran Avatar asked Jan 10 '12 09:01

fran


People also ask

Does XMLHttpRequest work with https?

There is nothing special needed to open HTTPS URLs via XMLHttpRequest. As long as the certificate and request are valid, it will work.

How do I send a request body in XMLHttpRequest?

The XMLHttpRequest method send() sends the request to the server. If the request is asynchronous (which is the default), this method returns as soon as the request is sent and the result is delivered using events. If the request is synchronous, this method doesn't return until the response has arrived.


1 Answers

This is going to fail for two reasons:

1) The url "https://www.gmail.com" actually tries to redirect you to "https://mail.google.com/mail/", which in turn will try to redirect you to a login page. This redirect is not being listed as an error

2) However more importantly, you cannot make XMLHttpRequests to a different domain, unless that domain supports CORS (http://www.html5rocks.com/en/tutorials/cors/). GMail does not support CORS, so this request will not work.

like image 163
monsur Avatar answered Sep 24 '22 19:09

monsur