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?
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.
You can delete your ExpressRoute circuit by selecting the Delete icon. Ensure the provider status is Not provisioned before proceeding.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With