Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Isomorphic JS - httpRequest client side only

Question about store data population in isomorphic flux apps. (I'm using react, alt, iso and node but theory applies to other examples)

I have a flux 'store' (http://alt.js.org/docs/stores/) that needs to get data from an api:

getState() {
   return {
       data : makeHttpRequest(url)
   }
}

and as the user navigates through the SPA, more data will be loaded via http requests.

I want this app to be isomorphic so that I can render the apps full html including latest data server side and return it to the user for fast initial page load.

react.renderToString() lets me render the app as html, and I can seed the data using alt&iso like:

storeData = { "MyStore" : {"key" : "value"}}; // set data for store
alt.bootstrap(JSON.stringify(storeData || {})); // seed store with data

var content = React.renderToString(React.createElement(myApp)); // render react app to html

The problem is that I will see errors when running the js server side as the store will want to make a http request which it wont be able to do (as xmlhttprequest wont exist in node)

Whats the best way to solve this problem?

The only solution I can think of would be to wrap the httprequest from the store with:

var ExecutionEnvironment = require('react/lib/ExecutionEnvironment');

    ...

    if (ExecutionEnvironment.canUseDOM) {
        // make http request
    } else {
        // do nothing
    }

Any better ideas? Thanks in advance.

like image 586
theStonehill Avatar asked Jul 09 '15 15:07

theStonehill


People also ask

Can Nodejs be used client side?

js application. In client-side we mainly deal with DOM or web APIs like cookies, but these things don't exist in Node. Other reasons why we cannot use node modules at the client side is that the node uses the CommonJS module system while the browser uses standard ES Modules which has different syntax.

What is isomorphic http request?

With Isomorphic JavaScript, when a client web page is first requested from the server, the view of the page is generated on the server, similar to server-side dynamic web pages, and sent over to the client. The client can then render the view immediately.

What is isomorphic rendering?

Isomorphic JavaScript means that the application uses a similar rendering engine on the server and the client. This rendering method makes it easier for developers to maintain markup templates, simplifying web development. Isomorphic rendering implies the use of Node. js/Io.

How do you use isomorphic react?

In Isomorphic process,when Developer authorizes client facing module ,there is a dependency of the module which requires a file containing secret data,Application is bundled with that file and sent to client with all secret and private data which an attacker can easily access by searching the bundle file .


1 Answers

I would recommend hooking into your Ajax library or XMLHttpRequest directly if you are running serverside. Just shim it with code that supplies data directly from your database or application.

A quick example:

var noop= function(){}

window.XMLHttpRequest= function(){
    console.log("xhr created", arguments);
    return {
        open: function(method, url){
            console.log("xhr open", method, url);
            // asynchronously respond
            setTimeout(function(){
                // pull this data from your database/application
                this.responseText= JSON.stringify({
                    foo: "bar"
                });
                this.status= 200;
                this.statusText= "Marvellous";
                if(this.onload){
                    this.onload();
                }
                // other libs may implement onreadystatechange
            }.bind(this), 1)
        },
        // receive data here
        send: function(data){
            console.log("xhr send", data);
        },
        close: noop,
        abort: noop,
        setRequestHeader: noop,
        overrideMimeType: noop,
        getAllResponseHeaders: noop,
        getResponseHeader: noop,
    };
}

$.ajax({
    method: "GET",
    url: "foo/bar",
    dataType: "json",
    success: function(data){
        console.log("ajax complete", data);
    },
    error: function(){
        console.log("something failed", arguments);
    }   
});

http://jsfiddle.net/qs8r8L4f/

I whipped this up in the last 5 minutes mostly using the XMLHTTPRequest mdn page

However if you are using anything not directly based on XMLHttpRequest or explicitly node aware (like superagent) you will probably need to shim the library function itself.

Other work to do on this snippet would be implementing errors and different content types.

like image 55
iSchluff Avatar answered Sep 18 '22 17:09

iSchluff