我成功地让ReactJS在服务器端工作,但我很难绕过我的客户端来回应。
就像我需要打开一切或其他东西。我没有通过ajax或任何东西获取数据,任何数据都在组件本身的JSON中。
我看到很多文字建议,但没有关于如何让它发挥作用的确切代码。 另外,我使用的是反应路由器。
其他背景,我使用commonJS和grunt来编译它。我在我的html文件中包含了编译的JS。当我点击按钮等时,没有任何反应。
服务器:
var React = require('react');
var Router = require('react-router');
var Express = require('express');
var fs = require('fs');
var routes = require('./src/routes');
var app = Express();
app.use('/dist', Express.static(__dirname + '/dist'));
app.use(function (req, res) {
// pass in `req.url` and the router will immediately match
Router.run(routes, req.url, function (Handler) {
var content = React.renderToString(React.createElement(Handler, null));
var index = fs.readFileSync('index.html', {encoding: 'utf8'});
res.send(index.replace('%%%content%%%', content));
});
});
var server = app.listen(9001, function () {
var host = server.address().address
var port = server.address().port
console.log('Example app listening at http://%s:%s', host, port)
})
路由器:
var React = require('react');
var Router = require('react-router');
var Route = Router.Route;
var DefaultRoute = Router.DefaultRoute;
//TODO: dynamically load each route somehow...
var App = require('./app');
var Home = require('./home');
var ItemInstance = require('./item-instance');
var Todo = require('./todo');
var Task = require('./task');
var Project = require('./project');
var Workspace = require('./workspace');
var routes = (
<Route name="index" path="/" handler={App}>
<Route name="home" path="/home" handler={Home} />
<Route name="workspace" path="/workspace" handler={Workspace} />
<Route name="instanceitem" path="/:tag/:id" handler={ItemInstance} />
<DefaultRoute handler={Home}/>
</Route>
);
module.exports = routes;