Reputation: 73
A simple Express app:
var express = require('express');
var app = express();
var router = express.Router();
function test (req, res, next) {
}
I'm trying to figure out the difference on these two implementations:
router.use('/myRoute', test)
router.post('/myRoute', function (req, res) {
});
And:
router.post('/myRoute', test, function (req, res) {
});
What I understand from the documentation (https://expressjs.com/en/4x/api.html#middleware-callback-function-examples) and (https://expressjs.com/en/4x/api.html#router.use) there is none. But that can't be the case?
Upvotes: 2
Views: 1694
Reputation: 5041
In the code you put as an example there's a difference:
router.use('/myRoute', test)
This will apply the "test" function to whatever request comes to /myRoute (POST, PUT, GET, etc).
While this:
router.post('/myRoute', test, function (req, res) {
});
Will only be applied to the POST request to /myRoute.
As for your question, the difference is that you either apply it globally, for example or you apply it only to a specific function. Depends the case you will use one or the other.
Upvotes: 3