Skip to content Skip to sidebar Skip to footer

Is There An Equivalent To The Apache Http Client In Javascript?

I am a new programmer whose primary background is in Java. I am attempting to write in fault handling to a program in Javascript as I would in Java. In java I use the Apache HTTP

Solution 1:

In javascript, as in some other languages, "exception" handling is mostly replaced by error checking. For example you'll check the status of your xmlhttprequest object when issuing a request :

httpRequest.onreadystatechange = function() {
    if (httpRequest.readyState === 4) {
        if (httpRequest.status === 200) {
                // ok, no "exception"
            } else {
                // BOOM ! "exception"
            }
        }
    }
}

Exceptions are only useful in a few places, like parseInt.

But I'm not sure that a heavy "fault tolerant" javascript code makes a lot of sense :

  • you really don't know where and how your code will be executed
  • all the important checks and all important persistence is client side

Your global system must be though with the idea that the browser is a foreign domain : nothing entering your server can be trusted.

Solution 2:

Here's the exact equivalent of your code snippet, but in JavaScript!

var cli;
 var callback = function(resp) {
    // due to the asynchronous nature of XMLHttpRequest, you'll need to put all logic that uses the response in a callback function.// code below using responseTextconsole.log(resp);
 };
 var timeout = 5000;
 var handler = function() {
    var errorSeries;
    if (this.readyState === 4) { // indicates complete
        errorSeries = parseInt(this.status.toString().charAt(0)); // will be "2" or "3" for 200 or 300 series responsesif (errorSeries === 2 || errorSeries === 3) {
            callback.call(this, this.responseText);
        } else {
            // handle http error here
        }
    }
 }
 for (var i = 0 ; i < 5 ; i++) {
 cli = newXMLHttpRequest(); // ActiveXObject('Microsoft.XMLHTTP') in IE8 and below
 cli.timeout = timeout;
 cli.onreadystatechange = handler;
 try {
    cli.open('GET','http://example.org/products');
    cli.send();
 }
 catch(e) {
 }

If the above looks wordy, that's because it is. Other commenters have steered you right: look into using a library like jQuery to abstract away this kind of boilerplate.

Post a Comment for "Is There An Equivalent To The Apache Http Client In Javascript?"