33

I have an app with following code for routing:

var router = express.Router(); 
router.post('/routepath', function(req, res) {});

Now I have to put routing code in different files so I tried to use this approach, but it is not working perhaps because instead of express.Router() it uses:

app.post("/routepath", function (req, res) {});

How can I put routing in different files using express.Router()?

Why app.get, app.post, app.delete, etc, are not working in app.js after using express.Router() in them?

Community
  • 1
  • 1
XIMRX
  • 2,130
  • 3
  • 29
  • 60

1 Answers1

29

Here's a simple example:

// myroutes.js
var router = require('express').Router();

router.get('/', function(req, res) {
    res.send('Hello from the custom router!');
});

module.exports = router;

// main.js
var app = require('express')();

app.use('/routepath', require('./myroutes'));

app.get('/', function(req, res) {
    res.send('Hello from the root path!');
});

Here, app.use() is mounting the Router instance at /routepath, so that any routes added to the Router instance will be relative to /routepath.

nbro
  • 15,395
  • 32
  • 113
  • 196
mscdex
  • 104,356
  • 15
  • 192
  • 153
  • works great for res.send thanks but functions declared in main.js are not accessible for routes in myroutes.js – XIMRX May 12 '14 at 12:13
  • 1
    If you have shared code like that, then put that code in a separate file/module (e.g. common.js) and simply require() them in your main.js and myroutes.js (and wherever else). – mscdex May 12 '14 at 12:15
  • Express 4.0 does not have `app.router` – Ravi Jan 03 '15 at 01:52
  • 4
    @RavishankarRajendran `require('express').Router()` != `app.router` – mscdex Jan 03 '15 at 01:57
  • @RavishankarRajendran Express 4 certainly [does have `require('express').Router`](http://expressjs.com/4x/api.html#router). – mscdex Jan 03 '15 at 03:09
  • _You no longer need to load app.router. It is not a valid Express 4 app object, so remove `app.use(app.router);`_. This text is from [Express Site](http://expressjs.com/guide/migrating-4.html). Also I think the routing middleware does not come with Express anymore by default. But one can install it manually. For these reasons I would stop using `router` and use `app.[method]` – Ravi Jan 03 '15 at 20:05
  • 1
    @RavishankarRajendran `app.router` has nothing to do with `require('express').Router` (which is an Express 4 thing). They are separate things. Mounting separate routers allows you to organize your routes better. A simple example of this is shown in my answer. – mscdex Jan 03 '15 at 20:17
  • What is app.router? – AturSams Apr 19 '17 at 10:49