user227719 user227719 - 4 months ago 31
Node.js Question

How to separate routes on Node.js and Express 4?

I want to separate Routes from my server.js file.

I am following this tutorial on Scotch.io
http://scotch.io/tutorials/javascript/build-a-restful-api-using-node-and-express-4

It is working if all lines are on server.js file. But I am failing to separate. How can I make this work?

server.js

// set up ======================================================================
var express = require('express');
var app = express();
var bodyParser = require('body-parser');

// configuration ===============================================================
app.use(bodyParser());

var port = process.env.PORT || 8000;

var mongoose = require('mongoose');
var database = require('./config/database');
mongoose.connect(database.url);
var Video = require('./app/models/video');

// routes =======================================================================
app.use('/api', require('./app/routes/routes').router);

// listen (start app with node server.js) ======================================
app.listen(port);
console.log("ready captain, on deck" + port);

module.exports = app;


And the app/routes/routes.js

var express = require('express');
var router = express.Router();

router.use(function(req, res, next) {
console.log('Something is happening.');
next();
});

router.get('/', function(req, res) {
res.json({ message: 'hooray! welcome to our rest video api!' });
});


router.route('/videos')

.post(function(req, res) {

var video = new Video();
video.title = req.body.title;

video.save(function(err) {
if (err)
res.send(err);

res.json({ message: 'Video criado!' });
});


})

.get(function(req, res) {
Video.find(function(err, videos) {
if (err)
res.send(err);

res.json(videos);
});
});

module.exports.router = router;

Answer

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

Comments