D
D
Dream82017-03-26 21:47:13
Node.js
Dream8, 2017-03-26 21:47:13

How to properly organize Express routing?

Hi, I'm writing a web-aplication and I've got a routing problem.
Here I connect controllers for routes:

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

Next, I add the location of the jade files for the controllers and add a few plugins:
var app = express();

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

app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(require('node-sass-middleware')({
  src: path.join(__dirname, 'public'),
  dest: path.join(__dirname, 'public'),
  indentedSyntax: true,
  sourceMap: true
}));
app.use(express.static(path.join(__dirname, 'public')));

And then the controllers themselves:
app.use('/', index);
app.use('/users', users);
app.use('/login', login);

But the problem is that the login controller is not executed.
Here he is:
var express = require('express');
var router = express.Router();

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

module.exports = router;

The beauty of the situation is that all the controllers before login work adequately.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
rustler2000, 2017-03-27
@Dream8

I won't say "exactly".
But I will tell you how not to.
0. It is not necessary to register slow and rarely used handlers earlier than more frequently called and more critical ones. But dependencies must be observed. Remember - the router registers handlers in a sheet (ok - array) and calls sequentially, in the order - in which they were registered.
1. No need to put express-static/serve-static before the main logic as dummyman (real nickname) advises. Don't you want the node to go to disk checking for the existence of a file every time, even when all you need to do is return an in-memory object?
2. Do not miss the 404 and 500 handlers. Otherwise, the client will be hurt, but it will be wonderful for you.
3. Don't forget that nginx distributes statics amazingly fast - because it uses sendfile, while the node will
read from disk and write to the socket in pieces.
Don't believe dummyman that nginx can't cache static.
You don't have to believe me - learn ab (you can also use strace to freak out how cool nginx works with statics).
4. There was also about SO_REUSEPORT but it will be a little offtopic.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question