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

express use routes in separate file
express route separation
node js routes in separate file
express routing best practices
express routes in different folder
express separate routes from controllers
express js
node js put routes in separate file

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;

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

Express Tutorial Part 4: Routes and controllers, Prerequisites: Read the Express/Node introduction. In addition to the views and routes the diagram shows "controllers" — functions that separate out the code to First we create routes for a wiki in a module named wiki.js. How to separate routes on Node.js and Express 4? Ask Question Asked 5 years, 6 months ago. Active 8 months ago. Viewed 71k times 58. 20. I want to separate Routes

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/

Keeping API Routing Clean Using Express Routers ― Scotch.io, Express apps utilize routers that are essentially containers for a set of middleware. We can put this middleware holder only on a certain route, which allows us to keep our logic in separate files and "start": "nodemon app.js". The most important stuff added to version 4 is Router API that provides us a Flexible Routing and RESTful. In any nodejs project, putting all the routes and its code inside server.js / app is terrible. Here's the easy way to separate Routes in Express 4 . Suppose you've created a fresh express 4 (check here for installation ) . Now lets coding .

Another way to separate routes into their own files with Express 4.0:

server.js

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

routes.js

module.exports = (function() {
    'use strict';
    var router = require('express').Router();

    router.get('/', function(req, res) {
        res.json({'foo':'bar'});
    });

    return router;
})();

How to add a Node.js Express route in a separate file, How to add a Node.js Express route in a separate file 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. // Startup Express App. var express = require( 'express' );. Putting routes in a separate file. Often times in Node.js, there will be a separate file which will contain all the routes for the application. This JavaScript file will handle the incoming http requests and assign correct routes as needed.

One way to separate routes into their own file.

SERVER.JS

var routes = require('./app/routes/routes');  //module you want to include
var app=express();
routes(app);   //routes shall use Express

ROUTES.JS

module.exports=function(app) {
 //place your routes in here..
 app.post('/api/..., function(req, res) {.....}   //example
}

How to modularize routes with the Express Router, If you're building in Node.js with the Express.js framework, you've probably First, we'll create a separate router instance for our API routes. Now that you understand the basics, let’s start to investigate these concepts further as we create our own Express application that involves multiple routes. Ensure you have Node.js installed from Node.js prior to following the next steps. Run the following in your terminal:

An issue I was running into was attempting to log the path with the methods when using router.use ended up using this method to resolve it. Allows you to keep path to a lower router level at the higher level.

routes.js

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

var posts = require('./posts');

router.use(posts('/posts'));  

module.exports = router;

posts.js

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

let routeBuilder = path => {

  router.get(`${path}`, (req, res) => {
    res.send(`${path} is the path to posts`);
  });

  return router

}

module.exports = routeBuilder;

If you log the router stack you can actually see the paths and methods

How to separate routes on Node.js and Express 4?, HTML � Java. 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� I'd like those routes to be accessed on a different port. Is there anyway to do this in express? In the code below, the "/factory" route (and other functionality) would be on one port, and the helper routes of "/killallthings", "/listallthings", and "/killserver" would be on a separate port. Here is a simplified version of the code:

NodeJS REST: How to Refactor Code into Multiple Files with Router , In this lesson, we'll create a dedicate routes file for any rout NodeJS REST: How to Duration: 14:10 Posted: 24 Apr 2018 If you want to put the routes in a separate file, for example routes.js, you can create the routes.js file in this way: module.exports = function(app) { app.get('/login', function(req, res) { res.render('login', { title: 'Express Login' }); }); //other routes.. } And then you can require it from app.js passing the app object in this way:

Separating Routes In Node.js Express 4, In any nodejs project, putting all the routes and its code inside server.js / app is terrible. Here's the easy way to separate Routes in Express 4 . Express router is a class library, it helps too create router and handle the HTTP request (such as GET, POST, PUT, DELETE, etc.). lets us see simple example for node js routes in a separate file using express. First we will install nodejs and create simple app. for it you can follow below example Url. Hello world application using nodejs and

node js routes in separate file using express, lets us see simple example for node js routes in a separate file using express. First we will install nodejs and create simple app. for it you can� I'm using Express 4 to provide routes to HTML/Jade files, and as well to provide an API. I want to separate routes from server file, and go even further- separate API from WWW. My code now looks like this: server.js

Comments
  • whats the node error? i think module.exports = { router: router } in routes.js should do it
  • Hi @bbuecherl, I am getting a ReferenceError: Video is not defined
  • It looks like you have lowercase 'v' for videos and trying to reference uppercase 'V' for videos.
  • Looks like he is not able to find Video, you need to move your line var Video = require("./app/models/video"); from server.js to routes.js.
  • When including video.js in route.js, use proper path something like "..\models\video"
  • This doesn't really separate the routes, it separates the controller. @Bikesh has the more correct solution.
  • I am trying to separate API from main app file then its showing error apiRoutes.post('/register', function(req, res, next) { ^ TypeError: Cannot read property 'post' of undefined at Object.<anonymous> (F:\saurabh_sharma\nodejs\salecrm\app\routes.js:4:10) at Module._compile (module.js:413:34) at Object.Module._extensions..js (module.js:422:10) ...
  • Perfect answer.
  • Clean answer (y)
  • how can this answer scale when i have more routes? @Bikesh
  • Why 'use strict'; inside the function?
  • @KarlMorrison I guess it's just to satisfy linters.