I created a controller with a single function that acts as a callback for the `GET /user/ request:
class UserController {
async getAllUserData(req, res) { /* retrieve data and return response */ }
async changePassword(req, res) { /* update password and return response */ }
}
const ctrl = new UserController();
api.get('/user', middlewareA, ctrl.getAllUserData);
api.post('/changePassword', ctrl.changePassword);
export default api;
Everything is working smoothly, where the middleware is only applied to the GET /user
route. However, my goal was to apply middleware to all functions within a single controller file and implement this at the level of my index.js
file, like so:
/* initialization... */
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Token');
res.header('Access-Control-Allow-Methods', 'POST, GET, PUT, DELETE, OPTIONS');
next();
});
app.use(middleware, UserController);
app.listen(3000, () => {
console.log('Example app listening on port 3000!');
});
However, in the second code snippet, since I placed the middleware before UserController, it gets applied to all methods - including the OPTIONS
requests sent by browsers - even though UserController
only has two methods using GET
and POST
.
Why does the middleware from the second snippet affect all methods? Do I need to add it separately to each function in every controller?