I can't find a good bare minimum example where I can wire up an express.js route to call a react view.
So far this is what I 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 do I tell express that JSX is my 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 do we call the route that will 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 then my index.htm page as well as generated jsx.
2021 edit:
the modern solution is to use the create-react-app tool, followed by dropping in your code where needed. It's been set up to do the rest for you. The React landscape has changed a fair bit over the last six years.
original 2015 answer:
The usual thing is to use react-router to take care of the routes; write your React app as a single React app (i.e. all your JSX source ends up bundled into a single app.js file, which knows how to load all your "pages" or "views") and then use express (or Hapi, or any other server process) mostly as your API and asset server, not your page/view generator.
You can then tap into the routes you set up in the react-router Router object so that on the express side you can forward your users to the URL that react-router can deal with for content loading, so you get
user request site.com/lol/monkeys
express redirects to /#/lol/monkeys
your react app loads the correct view because of the routes in Router
optionally, your app does a history.replaceState so that the user sees site.com/lol/monkeys (there are some react-router tricks to do this for you)
You can also automate most of this through server-side-rendering but the name can be confusing: you still write your React app as if there is no server involved at all, and then rely on React's render mechanism to fully render individual "pages" for a requested URL which will show all the right initial content while also then loading your app and silently hooking it back into the content the user is looking at, so that any interactions past the initial page load are handled by React again, and subsequent navigation is "fake" navigation (your url bar will show a new URL but no actual network navigation will happen, React simply swaps content in/out).
A good example for this is https://github.com/mhart/react-server-example
The other answers work with the usual way to use react, to replace an element in the dom like so
React.render(<APP />, document);
but if you want react to be your "template language" in express, you can also use react to render a simple string of html like so
app.get('/', function(req, res) {
var markup = React.renderToString(<APP />); // <-- render the APP here
res.send(markup); // <-- response with the component
});
there are a few other things you need to take care of in terms of bundling all the dependencies and working with jsx. this simple minimalist tutorial and this blog post helped me understand the situation better
note that the sample code in the tutorial uses this syntax
var markup = React.renderToString(APP());
which has been deprecated and will cause an error. to use it you'd have to replace
var APP = require('./app');
with
var APP = React.createFactory(require('./app'));
or just render jsx like i did in the first example. to get the tutorial to work i might have also had to use more recent versions of the dependencies in package.json.
once you've got that down a fancier tutorial shows a more powerful way to use react-engine to render react within express
If you want to keep it simple you can do this for the entry point of your app:
routes | index.js
app.get('/', function(request, response){
// how do we call the route that will run index.html ?
res.sendfile('../views/index.html');
});
React is going to target a specific element on your index.html page in it's render method:
React.render(<Application />, document.getElementById('foo'));
So if your javascript is included in index.html and an element with that id is present react is going to inject your Application into that div. From that point onwards you can do all of the routing with react-router OR you can setup different routes in express and handle them like you did index.html
Instead of manually dealing with React.render you can use a library called react-helper (https://github.com/tswayne/react-helper). It sets up a div for you, binds your react components to the div, allows you to pass properties to your components server side, and can even handle server-side rendering if you have webpack configured for your node app or are willing to use babel-register (not recommended for prod).
Related
I have a directory structure where the index.js file is located at:
path/to/home-page/src/routes
Note this is also the __dirname. And the html file is located at:
path/to/home-page/public/bootstrap/Homepage/page.html
I am serving the html document by relative path via:
const html_rel_dir : String = "../../public/bootstrap/Homepage/"
...
index.get('/homepage', (req, res, next) => {
var path_to_html = path.join(__dirname, html_rel_dir, 'homepage.html')
res.sendFile( path_to_html );
});
This smells "bad" to me in that the code will break if the directory structure changes, what is a better way to specify this?
Addendum, my app is configured so that public files are served via:
`this.app.use(express.static(path.join(__dirname, "public")));`
Using a View/Template engine can abstract the directory structure by letting you call out your view folder once at the top level. I use Nunjucks but its the same idea with the others. Handlebars, Mustache, etc. So my actual route calls look like this.
general-pages.routes.js
router.get('/feedback', function (req, res) {
var data = getSomeData()
res.render('general/feedback.html',data)
})
The framework early on in my main application was told the location of my views so from that point on it assumes any path is a subdirectory of my primary view folder. The one handler you see above handles lots of general pages. Then its referenced in my main app.js or whatever you call your main file like so:
app.use('/general',generalRoute)
So anything for /general goes to the generalRoute handler general-pages.routes.js defined earlier. The full URL to the user is /general/feedback
How does it know how to find my views?
nunjucks.configure('views', {
autoescape: true,
express : app
});
The code above says start looking for the folder called "views" inside the project folder. Its smart enough to use the internal node environment variables to determine the root directory. If you choose any of the other template engines they offer their own options for doing this.
First things first, version of various dependencies
Ubuntu - 15.04
NodeJS - 6.10.3
NPM - 3.10.10
Sails - 0.12.13
Second, here's what I did:
1. Installed Sails globally
2. In the directory /var/www, ran the command sails new app
3. Created a file UserController.js in api/controllers/v1
4. Created a file User.js in api/models
Code for UserController.js
module.exports = {
findOne: function(req, res) {
return res.send("Hello World!!! User -> findOne");
},
login: function(req, res) {
return res.send("Hello World!!! User -> login");
}
}
Code for User.js
module.exports = {}
Now, when I start my server using sails lift, here's what happens:
Browse http://localhost:1337/v1/user/1 - Page Not Found (404)
Browse http://localhost:1337/v1/user/login
Hello World!!! User -> Login
I know I'm going to sound silly, but I thought it is probably because I didn't use the Generator feature of Sails. So, here's what I did next: sails generate api v1/Product. And the file structure after this command is like this:
api
|-- controllers
|-- v1
|-- UserController.js
|-- V1
|-- ProductController.js
|-- models
|-- User.js
|-- V1
|-- Product.js
I wrote similar code in ProductController.js as I did in UserController.js and I expected that now the Product API should work but the result was same as in case of /v1/user/1.
As per the SailJS Blueprint API, this should have worked. So, can anyone explain why this is happening and how can I make /v1/user/1 and /v1/user/login both work as expected.
You have a couple of ways to achieve this. The first option is to set the restPrefix to /v1 inside config/blueprints.js
An optional mount path for all REST blueprint routes on a controller and it does not include actions and shortcuts routes.
This allows you to take advantage of REST blueprint routing even if you need to namespace your RESTful API methods
Now with same directory structure i.e., /controllers/v1/UserController.js and /models/User.js, you should be able to access both the /login and findOne methods.
The second option is to set the prefix to /v1 inside config/blueprints.js
An optional mount path for all blueprint routes on a controller, including rest, actions, and shortcuts.
This allows you to take advantage of blueprint routing, even if you need to namespace your API methods.
(NOTE: This only applies to blueprint autoroutes, not manual routes from sails.config.routes)
Now the directory structure would be /controllers/UserController.js and /models/User.js. You have the mapping /v1 setup for you.
On the other hand, you can completely turn off blueprint routes and set up your own routes inside /config/routes.js. This would give you more flexibility and you can also have environment specific routes inside config/env/[your_env].js
I want to create multiple apps within one app that will be hosted on the same server.
I am using the following link as a guide but I am unsure how to implement some of it:
Muliple spas
I have the app setup as follows:
src/
bower_components
apps/
app1/
app.js
index.html
app2/
app.js
index.html
Each index page has its own ng-app. I am using grunt-contrib-connect to serve the application for development. I have a middleware setup to default to app1:
middleware: function (connect, options, middlewares) {
var modRewrite = require('connect-modrewrite');
middlewares.unshift(modRewrite(['!\\.html|\\.js|\\.ts|\\.ttf|\\.woff|\\.eot|\\.svg|\\.css|\\.png$ /apps/app1/index.html [L]']));
return middlewares;
}
When I run the application app1 works as expected, but I am unsure how to navigate to app2 and have it bootstrap.
If I change the middleware to default to app2 it also works as expected so both apps run fine on their own.
How can i move to app2 and have it bootstrap? Do I need to map it someway in grunt-contrib-connect?
I have tried simply navigating to app2 using a href and $window.location.href but to no avail.
I've got one incredibly long index.js route file for my node/mongo/express application. Here is the structure.
app.js
/models
Schedule.js
Task.js
etc...
/routes
index.js
/public
/javascript
etc...
I want something like this
app.js
/models
Schedule.js
Task.js
etc...
/routes
index.js
schedule.js
tasks.js
etc...
/public
/javascript
etc...
How can I split up my index.js file?
For example, I have tried to do something like this in my app.js file
var routes = require('./routes/index');
var tasks = require('./routes/tasks');
// later in the file
app.use('/', routes);
app.use('/tasks', tasks);
However, it is not finding my task routes like it did before when I had only the index.js. This is probably because I took all the routes starting with "/task" from my routes/index.js and placed them in routes/task.js, but why express not recognizing the routes in this new file?
Any advice at all would be helpful, my friend and I are very new to the whole meanjs way of doing things, and basically cobbled together what we have from various tutorials. Now we desperately need to refactor, because routes/index.js is getting too long to work with. I did my best to do what makes sense intuitively, could anyone out there give advice on how to break up our routes file?
Well, the answer to this question lies in how you import (require in this context) the router instance. Each one of those files should do a module.exports with a router object or something similar where the routes can be mounted on the app instance you create.
For example, have a look at how I do it (with yeoman's help that is) in a project I have on GitHub here, then refer to how the router object is exported for each route like this example.
As another example of doing this, here is an open source project I've been contributing to here. Notice that we have a slightly similar approach here, then have a look at an example route declaration (with the corresponding export) here.
I come from a django background, and basically, the framework allows for a lot of modular code. I've created a simple blog engine in nodejs and express. However, all the routes end up being in my main app.js file, or rather app.coffee, since I used coffeescript for my nodejs applications, which complied to javascript.
So, say this is how my routes look:
app.get('/', index.index)
app.get('/users', user.list)
app.get('/blog', blog.blogList)
app.get('/blog/:id(\\d{5})', blog.blogEntry)
Now, the problem here is that if I want to sort these by categories, then this happens, then I would have to add another app.get function to the same file. Code:
app.get('/blog/categores/:cat(\w+), blog.someotherview)
If I wanted to add sorting according to time, for example:
app.get('/blog/time/:year(\\d{4}), blog.someYearView)
What I would like to do is delegate everything concerning /blog to be handled by blog.js for example. Ideally, how do I get all these routes out of the main app.js file?
You could easily do this by using the include() method in django.
Create an Express app in your app.js file, as you are used to. Then, do the same in the blog.js file. Import and use it within app.js as follows:
var blog = require('./blog');
var app = express();
app.use(blog);
Inside your blog.js file, all you need to do is to export your app:
var app = express();
app.get('/blog/...', ...);
module.exports = app;
To put it in other words: Any Express app can be used as middleware for any other Express app, hence you can create sub-apps.
Hope this helps.
PS: TJ Holowaychuk (the creator of Express) created a video on this, Modular web applications with Node.js and Express.