同构JS – 只有httpRequest客户端

关于同构stream量应用中商店数据总量的问题。 (我正在使用的反应,ALT,ISO和节点,但理论适用于其他的例子)

我有一个stream量'商店'( http://alt.js.org/docs/stores/ ),需要从api获取数据:

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

当用户在SPA中导航时,更多的数据将通过http请求加载。

我希望这个应用程序是同构的,以便我可以呈现应用程序完整的HTML包括最新的数据服务器端,并返回给用户的快速初始页面加载。

react.renderToString()允许我将应用程序呈现为html,并且可以使用alt&iso来播种数据:

 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 

问题是,当运行js服务器端时,我会看到错误,因为商店将要发出一个http请求,这是不可能的(因为xmlhttprequest不会存在于节点中)

什么是解决这个问题的最好方法?

我能想到的唯一解决scheme是将商店中的httprequest包装在:

 var ExecutionEnvironment = require('react/lib/ExecutionEnvironment'); ... if (ExecutionEnvironment.canUseDOM) { // make http request } else { // do nothing } 

任何更好的想法? 提前致谢。

如果您正在运行服务器端,我build议直接连接到您的Ajax库或XMLHttpRequest。 只需使用直接从数据库或应用程序提供数据的代码即可实现。

一个简单的例子:

 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/

我在最后5分钟内使用了XMLHTTPRequest mdn页面,

但是,如果您使用的不是直接基于XMLHttpRequest或显式节点感知(如superagent)的任何东西,您可能需要填充库函数本身。

其他工作要做这个片段将实施错误和不同的内容types。