Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why the /users route in Express and Node?

Edit: The default express app is this:

var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

var routes = require('./routes/index');
var users = require('./routes/users');
----------------------------------------
These refer to files that look like:

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

/* GET home page. */
router.get('/', function(req, res) {
  res.render('index', { title: 'Express' });
});

module.exports = router;
------------------------------
var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

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

// catch 404 and forward to error handler
app.use(function(req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
    app.use(function(err, req, res, next) {
        res.status(err.status || 500);
        res.render('error', {
            message: err.message,
            error: err
        });
    });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
        message: err.message,
        error: {}
    });
});


module.exports = app;

However, the documentation says:

// this middleware will not allow the request to go beyond it
app.use(function(req, res, next) {
  res.send('Hello World');
})

// requests will never reach this route
app.get('/', function (req, res) {
  res.send('Welcome');
})

So my question, is why would a request ever make its way to the /users route when a default (i.e. '/') route has already been specified? Is it because routes and users are not functions?

On a related note, why even specify the / if that is what is used by default each time?

Lastly, the default app specifies the '/users' route: Why not just put another path in the index.js route? I am confused how the app can specify app.use('/users', users) and then, in the users route, specify

router.get('/', function(req, res) {
  res.send('respond with a resource');
});

What does the / correspond to? It seemed like all requests to / would be handled by the first route (the one that use the routes default file)

like image 277
Startec Avatar asked Oct 19 '14 03:10

Startec


2 Answers

There are two routers in the Express 4 application skeleton: routes (mounted on '/') and users (mounted on '/users'). You may use both of them or only routes or you may even add more routers.

app.js:

var routes = require('./routes/index');
var users = require('./routes/users');
app.use('/users', users);  // please note the mounting point!
app.use('/', routes);

users.js

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

router.get('/', function(req, res, next) {  
  res.send('respond with a resource');
});

module.exports = router;

Please note that router.get('/', ... ) for the users router means that the requested url is http://yourserver/users and not http://yourserver/

like image 31
mk12ok Avatar answered Sep 21 '22 15:09

mk12ok


app.use() is middleware. You pass it an optional path and a function and it is the function's job to decide if it wants to pass the request on to further middleware or further routes. It does that by calling next() or if it doesn't want to pass it on, it doesn't call next().

So, if you have:

app.use("/", fn);

That middleware will get called for all paths, but the code inside the function you pass it decides whether to pass the request on or not.

like image 142
jfriend00 Avatar answered Sep 25 '22 15:09

jfriend00