Handling HTTP requests in isomorphic javascript

I have a purely external javascript project that contains several models that encapsulate various interactions with various RESTful web services. My goal is to pull these models into my own npm module so I can use them server side in a new node application I am writing.

The models use an XMLHttpRequest object which will obviously be undefined on the server. I cannot require ("http") in my models, because then the browser will throw an error when trying to create for the client.

How can I handle HTTP requests that will work on both the server and client? I would like something like:

var ajax = {
    get: function (url, opts) {
        if (typeof XMLHttpRequest === 'undefined') {
            // is node app
            var http = require('http');
            ...
        } else {
            // is browser app
            var xhr = new XMLHttpRequest();
            ...
        }
    },
    post: ...
};

      

+3


source to share


1 answer


Superagent standard . The APIs are the same whether you are on the client (xhr) or server (http), so there is no need to duplicate code or check which protocol to use. There's also libraries that turn it into promises too, which is really nice.



+1


source







All Articles