What is the difference between next() and next('route') in an expressjs app.VERB call?

后端 未结 2 1375
星月不相逢
星月不相逢 2021-01-30 12:59

The docs read:

The app.VERB() methods provide the routing functionality in Express, where VERB is one of the HTTP verbs, such as app.post(). Multiple

相关标签:
2条回答
  • 2021-01-30 13:28

    I hated it when I answer my own question 5 minutes later. next('route') is when using route middleware. So if you have:

    app.get('/forum/:fid', middleware1, middleware2, function(){
      // ...
    })
    

    the function middleware1() has a chance to call next() to pass control to middleware2, or next('route') to pass control to the next matching route altogether.

    0 讨论(0)
  • 2021-01-30 13:30

    The given answer explains the main gist of it. Sadly, it is much less intuitive than you might think, with a lot of special cases when it is used in combination with parameters. Just check out some of the test cases in the app.param test file. Just to raise two examples:

    1. app .param(name, fn) should defer all the param routes implies that if next("route") is called from a param handler, it would skip all following routes that refer to that param handler's own parameter name. In that test case, it skips all routes refering to the id parameter.
    2. app .param(name, fn) should call when values differ when using "next" suggests that the previous rule has yet another exception: don't skip if the value of the parameter changes between routes.

    ...and there is more...

    I'm sure there is a use-case for this kind of next('route') lever, but, I agree with previous comments in that it certainly makes things complicated and non-intuitive.

    0 讨论(0)
提交回复
热议问题