Ads Top

Using Fetch For Javascript Network Requests

XMLHttpRequest, XHR for short , is one of the most important terms in the history of web development. It looks like a complicated term but it is simply an API that handles transferring data between the web browser and a web server.

Its biggest use case is is retrieving data for an already loaded web page, creating the look and feel of a desktop app in a web browser.

Quick History

Making an Old School Ajax Request

First you have to setup your object. The try catch method is a way of handling different browsers. (ActiveXObject is a Microsoft thing)

function makeHttpObject() {
  try {return new XMLHttpRequest();}
    catch (error) {}
  try {return new ActiveXObject("Msxml2.XMLHTTP");}
    catch (error) {}
  try {return new ActiveXObject("Microsoft.XMLHTTP");}
    catch (error) {}

  throw new Error("Could not create HTTP request object.");
}

show(typeof(makeHttpObject()));
Once you have that instantiated you can then make a request as shown below


var request = makeHttpObject();
request.open("GET", "files/fruit.txt", false);
request.send(null);
print(request.responseText);
Making the Request With jQuery
jQuery came along and abstracted some of the boilerplate code needed previously. It looked cleaner, but still, you are using jQuery. An example using jQuery:


$.ajax({
    url : url,
    method : 'GET',
    beforeSend : function(req) {
        req.setRequestHeader('Authorization', auth);
    }
});
3rd party libraries
With the release of NPM in 2010, there are literally hundreds of options to install packages that deal with HTTP Requests in your project. Many of these are fine and do what they advertise for the most part, but with the Fetch API being added to ES6, it is worth taking notice and doing your networks request.

3rd Party VS Native Libraries
I find it good practice that when presented with the opportunity to use a native library, go that route when possible. Whenever you install an NPM module you are adding size and dependencies to your application. While many of these size increments may be trivial, I find that every little bit counts in the end, so do what you can to reduce size up front.

Using Fetch

Now, with ES6, we finally have a built in API for dealing with network requests. It is called Fetch (Fetch API). Fetch will make a request, return a promise (Promises Explained), and do something with that. The basic usage for fetch is fairly straight forward. For example.


fetch('https://weather.com/get/temp/city=some_city', {
    method: 'get'
}).then(function(response) {
    // Get the temperature and make a decision 
}).catch(function(err) {
    // Could not get the temp 
});

You can also chain promises

fetch('https://weather.com/get/temp/city=some_city', {
    method: 'get'
}).then(function(response) {
    // Get the temperature and make a decision 
}).then(function(response2) {
    // Get response2 and make another decision about something else
}).catch(function(err) {
    // Could not get the temp 
});

In this example, you make a call to weather.com/get/temp/city=some_city where you should expect a temperature to return. If it is, then it does something with that response, and if not, it returns an error.

A quick note:
Fetch is a relatively new feature so it will not work with legacy browsers. You can check compatibility here http://caniuse.com/#search=fetch

Because of this, if you implement fetch (you should), you have to use the fetch-polyfill if you are going to be supporting older browsers. Check out Fetch polyfill in order to support older browsers.

Also, keep in mind that since fetch returns a promise, you also will need to provide a promise polyfill since Promises are relatively new as well. Promise Polyfill.

No comments:

Powered by Blogger.