Dims
Dims

Reputation: 51039

How to set routes in Express? app.use() vs app.get()

I have site stub, where routing is set in 2 places.

First in app.js:

...
var index = require('./routes/index');
var users = require('./routes/users');
...
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', index);
app.use('/users', users);
...

something is set with use. Next inside referred scripts, like index.js:

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

var fs = require('fs');
var path = require('path');
var config = require('../config');

/* GET home page. */
router.get('/', function(req, res) {

    var data = {};
    ...

Suppose I wish to use infromation from Express Routing doc. Where I should put the routing for, say, /users/:userId/books/:bookId?

In docs, get is called against app, while in my stub, get is called against router and in two-step manner.

Where to hook?

Upvotes: 4

Views: 12400

Answers (2)

Vasileios Pallas
Vasileios Pallas

Reputation: 4877

In docs get is called against app because they set their endpoints in app.js file. In your index.js you return the router from the file with module.exports = router;, which is app's router. Now in your app.js file says

app.use('/', index);
app.use('/users', users);

These are the routes. You are saying that all the endpoints which are in index file are starting with / and the endpoints which are in users file are starting with /users.

So the route /users/:userId/books/:bookId must be in users.js file like this

router.get('/:userId/books/:bookId', function(req, res, next) {
   // do something
});

Upvotes: 6

Mohit Bhardwaj
Mohit Bhardwaj

Reputation: 10083

If you want to handler this route - /users/:userId/books/:bookId, then you need to write following handler in your routes/users.js file.

router.get('/:userId/books/:bookId', function(req, res) {
    var data = {};
});//get route

Basically, in app.js you are categorising url's based on its first part e.g. users. So, all your routes that start with /users will be handled by your routes/users.js class. All other routes will be handled by routes/index.js, because that is defined to handle / (there is no /users, /admin etc. so all routes that are not handled by users.js can be handled in this.)

Also, in these route handler files, you define a router object, add all route handlers to it and export it at the bottom. So when you are in these files, you need to use router and in app.js you can directly use app.get() etc.

Upvotes: 1

Related Questions