1

I am currently writing a very basic HTML application which uses JavaScript to make a call to a REST API (for what it's worth, it's the HBase REST API). Currently my call does not give any appropriate response: response code of 0 (which I understand is not a legitimate response code, but essentially an empty response); empty statusText; empty responseText.

My instinct with this kind of response would be that the problem is with my URL; I therefore output the URL. The URL ends up being as follows: http://hbase_server.com:8080/table_name/key

I then executed curl -i http://hbase_server.com:8080/table_name/key and this gave me exactly the response I was expecting, indicating that my URL at least is correct, and therefore the problem must be with my request. I'm posting the code below. Since I have incredibly limited experience with JavaScript, it is very likely I have made an obvious error.

function sendRequest()
{
    var key = document.getElementById("Key").value;
    var url = "http://hbase_server:8080/table_name/" + key + "";
    var req = new XMLHttpRequest()
    // Create the callback:
    req.onreadystatechange = function() {
        if (req.readyState != 4) return; // Not there yet
        if (req.status != 200) {
            document.getElementById("result").innerHTML = "Status: " + req.statusText;
            return;
        }
        // Request successful, read the response
        var resp = req.responseText;
        document.getElementById("result").innerHTML = resp;
    }
    req.open("GET", url, true);
    req.send();
    document.getElementById("result").innerHTML = url;
}
swinefish
  • 559
  • 6
  • 22
  • Did you ever consider using [jQuery](https://jquery.com/)? –  May 24 '16 at 11:43
  • For this to work you need to call the rest from the same domain and port: `http://hbase_server.com:8080`, e.g. the call should be `var url = "/table_name/" + key + "";` or implement CORS on the server (search for "CORS javascript") – mplungjan May 24 '16 at 11:43

2 Answers2

2

Due to same-origin policy, you won't be able to fetch the data using XHR unless the requesting page is on the same domain or the server sets the appropriate CORS headers.

Try opening the browser's developer console to see if there is an error related to this.

Shira
  • 6,392
  • 2
  • 25
  • 27
  • I've never been much of web developer, thanks for pointing me to the developer console. It is the error you mentioned. – swinefish May 24 '16 at 12:19
  • In the case mentioned, make sure your data type is specified as jsonp. https://en.wikipedia.org/wiki/JSONP – Anthony Mason May 24 '16 at 18:20
1

You're suffering from what is known as "Same-origin policy". Your client is preventing your code to make calls to the URL you're using in your request because it differs from the domain where the code was loaded from (i.e. localhost).

Dave Van den Eynde
  • 17,020
  • 7
  • 59
  • 90