Home > Net >  Basic Express Routes puzzle
Basic Express Routes puzzle

Time:08-14

I got stuck in Mozilla js tutorial and need help. Here are excerpts from 3 files:

a)

the 2 pieces from app.js file show where to find Router handlers and then where to present them (my guess)

    //app.js
    //the following 3 vars do sit in routes folder, code copy-pasted var 3 my addition
    var indexRouter = require('./routes/index');
    var usersRouter = require('./routes/users');

    var coolRouter = require('./routes/cool');

    var app = express();

    ....

    //the following 2 'use' work just fine, the third sends err 404, 'not found'
    app.use('/', indexRouter);
    app.use('/users', usersRouter);

    app.use('/users/cool', coolRouter);

b) part of the users.js sitting in routes folder:

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

c) part of the cool.js copied from the previous and sitting in routes folder:

    /* GET cool text. */
    router.get('/', function(req, res, next) {
      res.send('you are cool, kid!');
    });

I'd like to get it why it does not work.

CodePudding user response:

The reason you cannot reach /users/cool is that your request is being cathed by the /users endpoint. In order for your code to work as you intend it to do, you will have to place your routes like this:

app.use('/', indexRouter);
app.use('/users/cool', coolRouter);
app.use('/users', usersRouter);

With the /users/cool endpoint before the /users endpoint. That way, the request to /users/cool will not be catched by another endpoint.

CodePudding user response:

I am sorry for the inarticulate presenting of my question/problem. It got exhaustively resolved by the answer of Eric Qvarnström. Thank you, Eric! You are my hero!

  • Related