Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to skip route middleware in node express?

Take the following POST function in express. (I am using express 3.5.1)

app.post('/example', someFunctionOne, someFunctionTwo, function(req, res){
    if(!req.someVar){
        return res.send(400, { message: 'error'});
    } else{
        return res.json(200, { message: 'ok'}); 
    }
});

If I get some result from someFunctionOne which means someFunctionTwo is redundant, is there a way to skip someFunctionTwo and go to the last unnamed function which will send the response?

So I guess in the same way there is the "next()" function where is the "last()" function? If this is not possible why not? It seems like an oversight to me but is there a good reason?

like image 555
Paulie Avatar asked Jul 19 '14 12:07

Paulie


People also ask

How do I skip the middleware Express?

To skip the rest of the middleware functions from a router middleware stack, call next('route') to pass control to the next route. NOTE: next('route') will work only in middleware functions that were loaded by using the app.METHOD() or router.METHOD() functions.

How do I get rid of Express route?

You can delete your ExpressRoute circuit by selecting the Delete icon. Ensure the provider status is Not provisioned before proceeding.

Can we use multiple middleware in node?

We can use more than one middleware on an Express app instance, which means that we can use more than one middleware inside app. use() or app. METHOD() . We use a comma ( , ) to separate them.

Why do we need middleware in Express?

An Express-based application is a series of middleware function calls. Advantages of using middleware: Middleware can process request objects multiple times before the server works for that request. Middleware can be used to add logging and authentication functionality.


1 Answers

My instinct is to do something like this:

const funcOne = (req, res, next) => {
  // do something
  if (/* you were successful */) {
    res.locals.shouldSkipFuncTwo = true
  }
  next()
}

const funcTwo = (req, res, next) => {
  if (res.locals.shouldSkipFuncTwo) return next()
  // do whatever stuff
  next()
}

router.get('/', funcOne, funcTwo, (req, res) => {
  res.status(200).send('hello world')
)}

If you haven't used res.locals before, here are the express docs on it. Basically, it's a property in the response object that's there for you to use as a container.

like image 152
JSilv Avatar answered Oct 08 '22 07:10

JSilv