NodeJS Express Routing(Express4)


Routing is one of important part in Express.
This decides URL and view and action. Rails also has route file.
In express4, route file includes actions.

How to make file?

1 file 1 sub url
For example

route filename what?
/ index.js root actions
/users users.js user actions

All files are in routes directory.

Learn from Default Template

We can see example from blank express application after express command


See app.js. Routing part is following

Routing for Express4

app.route() : Handler
express.Router : modular mountable route handlers

Express Default(Express4)

Create express4 project from express-generator
By default, auto-generated app.js has basic codes.


Please be careful order, first is prior.

// Routing file
var routes = require('./routes/index');
var users = require('./routes/users');

// This is last of use(before routing)
app.use('/', routes);  // Routes   middleware style
app.use('/user', users); // Add /user sub

The order is important.
routes is applied first, and /user is next.
The second file overrides first file, first file settings are ignored, it’s useless.
routes/index.js, routes/users.js are routing(action) file.
app.use is middleware setting. use means apply. In this case, / applies routes(=index.js)


Let’s see index.js first.
index.js indicates /. We define under / action
(user.js is /users, if you use / in users.js, it means /users/…)

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

router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });

// Add Action here

// GET /

module.exports = router; // Don't forget!

Import module, it decides route.
Everytime we add new sub, we add use and routes/xx.js, it is simple, isn’t it?

Other examples

This is admin example.

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

/*  /admin  */
adminRoutes.get('/', function(req, res, next) {
    res.render('admin/admin', {title: "TOP"});  // view/admin/admin.ejs

/* /admin/list */
adminRoutes.get('/list', function(req, res, next) {

/* /admin/list POST */'/list', function(req, res, next) {
   var keyword =;  // name='search'
   res.render('admin/list', { word: keyword });

/* /admin/delete/:id Delete Ajax */'/delete/:id', function(req, res, next) {
   var id =  //  /:id
   if (id == null || id.length == 0) {
      res.redirect('/');  //   root /  not /admin in redirect case


Migrating to Express 4