简体   繁体   中英

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: ...
};

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM