javascript - Calling React View from Express -
i can't find bare minimum example can wire express.js route call react view.
so far have.
+-- app.js +-- config | +-- server.js +-- routes | +-- index.js +-- views | +-- index.html
app.js
require('./config/server.js'); require('./routes/index.js');
config | server.js
"use strict"; var express = require('express'), app = express(), routes = require('./routes'); app.set('view engine', 'html'); app.engine('html', ); // how tell express jsx template view engine? var port = process.env.port || 3000; app.engine('handlebars', exphbs({ defaultlayout: 'main'})); app.set('view engine', 'handlebars'); var server = app.listen(port, function(){ console.log('accepting connections on port ' + port + '...'); });
routes | index.js
app.get('/', function(request, response){ // how call route run index.html ? request.render('index'); });
views | index.html
<!doctype html> <html> <head> <script src="build/react.js"></script> <script src="build/jsxtransformer.js"></script> <script type="text/jsx" src="build/noepisodes.js"></script> </head> <body> <div id="noepisodesmessage"></div> </body> </html>
and index.htm page generated jsx.
the usual thing use react-router take care of routes, write react app single react app (i.e. jsx source ends bundles single app.js file, knows how load "pages" or "views") , use express (or hapi, or other server process) api , asset server, not page/view generator.
you can tap routes set in react-router
router object on express side can forward users url react-router
can deal content loading, get
- user request site.com/lol/monkeys
- express redirects /#/lol/monkeys
- your react app loads correct view because of routes in router
- optionally, app history.replacestate user sees site.com/lol/monkeys (there react-router tricks you)
you can automate of through server-side-rendering name can confusing: still write react app if there no server involved @ all, , rely on react's render mechanism render individual "pages" requested url show right initial content while also loading app , silently hooking content user looking at, interactions past initial page load handled react again, , subsequent navigation "fake" navigation (your url bar show new url no actual network navigation happen, react swaps content in/out).
Comments
Post a Comment