0

I have a doubt about middelware in express.

I want to many thinks in one middleware. For example

I have this code y me middleware

module.exports = function(req,res,next) {
    if(req.method === 'GET') {
        res.end('GET method not supported');
    } else {
        next();
    }
}; 

and I use it like this

app.route('/', <the_middleware>, (res, req, next) => {
 // Code
})

But I am wondering if is possible to do something like this

app.route('/', <the_middleware>.<the function1>, (res, req, next) => {
     // Code
    })

app.route('/', <the_middleware>.<the_function2>, (res, req, next) => {
     // Code
    })

is there a possiblitity to do something like

 function function1 (req,res,next) {
        if(req.method === 'GET') {
            res.end('GET method not supported');
        } else {
            next();
        }
    }; 

 function function2 (req,res,next) {
        if(req.method === 'GET') {
            res.end('GET method not supported');
        } else {
            next();
        }
    }; 

module.exports = <I don`t know what go here>

Thanks.

Update. IT works, my code now is

The router

router.post('/', checkAuth.sayHi, checkAuth.sayBye, (req, res, next) => {

    console.log('good');
    res.status(200).send('it works');
    console.log('yes');

});

The middleware

module.exports = {

    sayHi(req, res, next) {
        console.log('hi');
        next();

    },

    sayBye(req, res, next) {
        console.log('bye')
        next();
    }
};
1
  • Why not do app.get('/', function() { throw new Error('GET not supported'); }) or something? Commented Apr 7, 2019 at 21:21

1 Answer 1

1

You can just export an object containing both functions:

module.exports = {
  function1,
  function2
}
Sign up to request clarification or add additional context in comments.

1 Comment

Yes, but, how do I use it in a route?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.