Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling HTTP requests in isomorphic javascript

I have a purely front-end javascript project that contains a number of models that encapsulate different interactions with various RESTful web services. My goal is to pull these models into their own npm module in order to have them used server-side in a new node app I'm writing.

The models use the XMLHttpRequest object, which obviously will be undefined on the server. I can't require('http') in my models, because then browserify will throw an error when I try to build for the client.

How can I handle for HTTP requests that will work on both server and client? What I'd like is 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: ...
};
like image 773
Danny Avatar asked May 20 '26 14:05

Danny


1 Answers

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

like image 90
BradByte Avatar answered May 22 '26 02:05

BradByte



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!