How to separate routes on Node.js and Express 4?
Solution 1:
Server.js
var express = require('express');
var app = express();
app.use(express.static('public'));
//Routes
app.use(require('./routes')); //http://127.0.0.1:8000/ http://127.0.0.1:8000/about
//app.use("/user",require('./routes')); //http://127.0.0.1:8000/user http://127.0.0.1:8000/user/about
var server = app.listen(8000, function () {
var host = server.address().address
var port = server.address().port
console.log("Example app listening at http://%s:%s", host, port)
})
routes.js
var express = require('express');
var router = express.Router();
//Middle ware that is specific to this router
router.use(function timeLog(req, res, next) {
console.log('Time: ', Date.now());
next();
});
// Define the home page route
router.get('/', function(req, res) {
res.send('home page');
});
// Define the about route
router.get('/about', function(req, res) {
res.send('About us');
});
module.exports = router;
*In routs.js you should define Middle ware
ref http://wiki.workassis.com/nodejs-express-separate-routes/
Solution 2:
As far as separating routes from main file is concerned..
Server.js
//include the routes file
var routes = require('./routes/route');
var users = require('./routes/users');
var someapi = require('./routes/1/someapi');
////////
app.use('/', routes);
app.use('/users', users);
app.use('/1/someapi', someapi);
routes/route.js
//last line - try this
module.exports = router;
Also for new project you can try on command line
express project_name
You will need express-generator for that