なっく日報

技術やら生活やらのメモ

Expressのapp.useが記述した順で動かない?

基本的には設定した順に動く

v4からは公式(http://expressjs.com/en/4x/api.html)にある通り、

Middleware functions are executed sequentially, therefore the order of middleware inclusion is important.

つまり、設定した順序でmiddlewareが適用されるということになってます。

// 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');
});

だと、Welcomeは出力されません。

しかし注意点

app.useの間に一個でもapp.(all|get|post|put|delete)が出てきたらその後のapp.useは全て無効になってしまいます。

例えば

app.use('/foo', (req, res, next) => {
  console.log(1);
  next();
});
app.all('/foo/*', (req, res, next) => {
  console.log(2);
  next();
});
app.use('/foo', (req, res, next) => {
  console.log(3);
  next();
});
app.get('/foo/bar', (req, res) => {
  console.log(4);
  res.send('yo');
});

これだと、/foo/barにアクセスしても3が出力されません。

app.use('/foo', (req, res, next) => {
  console.log(1);
  next();
});
app.all('/baz/*', (req, res, next) => {
  console.log(2);
  next();
});
app.use('/foo', (req, res, next) => {
  console.log(3);
  next();
});
app.get('/foo/bar', (req, res) => {
  console.log(4);
  res.send('yo');
});

app.all('/baz/*'みたいにパスが違っていてもダメ。

とにかく間に出てきたらダメ。

どうすればよいか

あたりを守っていけばいいんじゃないでしょうか。

大したことないように思いますが、意外と嵌ったのでご注意を。