I want to stop execution if a determinate param is true when I called a function. Is that possible?
The only way I found to do that is returning a boolean in check function and depend of it do a return or not in router.get.
router.get('/', function(req, res){
check(req, res, true);
console.log(1);
res.render('page1', {});
});
function check (req,res,param = false){
if (param){
res.render('page2');
// Stop it here
}
else {
return("hi");
}
}
Something like this (I assume that function check_param return true if your parameter param set).
router.get('/',[function(req,res,next) {
if (check_param()) {
res.render('page2');
}
else {
next();
}
},function(req,res) {
res.render('page1',{});
}])
You can create a middleware and add param check logic there so that you can use it for multiple routes.
router.get('/', check, function(req, res){
res.render('page1', {});
});
function check (req, res, next){
if (req.param){
res.render('page2');
}
else {
next()
}
}
Related
I am writing a middleware function that looks for validation errors and if the error is found gives out a certain output else continues the program flow. I have two functions with the exact code but they check for different schemas.
My first function runs without any exception. However, when I try to execute the second function I get an error in the console.
const validateCampground = (req, res, next) => {
const { error } = campgroundSchema.validate(req.body);
if (error) {
const msg = error.details.map((el) => el.message).join(",");
throw new ExpressError(msg, 400);
} else {
next();
}
};
const validateReview = (req, res, next) => {
const { error } = reviewSchema.validate(req.body);
if (error) {
const msg = error.details.map((el) => el.message).join(",");
throw new ExpressError(msg, 400);
} else {
next(); //this is the point where the exception occurs
}
};
It is only inside the validateReview function where next middleware function is not recognised as a valid function.
The problem was not with the next() middleware but instead it was with the route as I was wrapping the route with the validateReview function.
I was doing something like this :
app.post(
"/campgrounds/:id/reviews",
validateReview(
catchAsync(async (req, res) => {
//my Logic here
})
));
Whereas , I should have been doing something like this :
app.post(
"/campgrounds/:id/reviews",
validateReview,
catchAsync(async (req, res) => {
//my logic here
})
);
hi if you want to use a middileware
exports.middileware = (req,res,next)=>{
try{
//middileware logic
next();
}catch(err){
//print the error
})
}
}
and call the exported middileware file in requires file to check the middileware function
const { middileware } = require('path');
and use like this
router.get('/routename',middleware,nextfunction) //router you can choose as you like get,post,patch anything
try this out
I got this error when I omitted "req" and "res" in the function's parameters. When I added them, the error disappeared. Since I was using typescript, the first scenario looked like this:
function traceRoute(next){
console.log(routeTrace);
next();
}
Corrected to:
function traceRoute(req, res, next){
console.log(routeTrace);
next();
}
I'm actually using loopback, and here is my needs:
I have two middlewares triggered by a POST request on /api/Orders/, and I need middleware 1 to pass data to middleware 2.
For example:
middleware1.js
module.exports = function() {
return function firstMiddleware(req, res, next) {
var toPass= "string to pass to second middleware";
next();
};
}
middleware2.js
module.exports = function() {
return function secondMiddleware(req, res, next) {
//Do whatever to get passed value from middleware1
};
}
I did not found anything useful in the official documentation talking about this, but I may have missed it.
Thanks.
In middleware1 you can update req object and access the variable in the middleware2.
middleware1.js
module.exports = function() {
return function firstMiddleware(req, res, next) {
var toPass= "string to pass to second middleware";
req.locals = { toPass };
next();
};
}
middleware2.js
module.exports = function() {
return function secondMiddleware(req, res, next) {
console.log(req.locals.toPass);
next();
};
}
I have created some standard middleware with some logic, and depending on the logic I need to call some 3rd party middleware.
Middleware is added using app.use(), which is where I add my custom middleware.
Once in my middleware I no longer have access to app.use(), how do I call the middleware?
Here is some code:
Any ideas ?
const customerData = (req, res, next) => {
try {
console.log('Started');
if (process.env.STORE_CUSTOMER_DATA === 'true') {
// Here is some custom middleware that doesn't belong to me
//
// Returns a function (I confirmed it) ready to be called with res,req, next
//
let externalMiddlware = logger({
custom:true
});
// Do I return it ? Call it ? Trying everything and nothing seems to work
externalMiddlware(req,res,next); // ???
} else {
// DO not call external middleware, will break out of if and then call next()
}
console.log('Finished');
next();
} catch (err) {
next(err);
}
};
module.exports = customerData;
I think this should work but if you delegate the callback to this other externalMiddlware you should not call next() in customerData use this 3rd middleware
so have you try
const customerData = (req, res, next) => {
try {
console.log('Started');
if (process.env.STORE_CUSTOMER_DATA === 'true') {
let externalMiddlware = logger({
custom:true
});
return externalMiddlware(req,res,next);
} else {
return next(); // <= next moved
}
} catch (err) {
next(err);
}
};
module.exports = customerData;
I'm trying to setup a simple system for rendering user-input-errors and stopping propogation in express, this is what I've got so far:
routingFunction= (req, res, next) {
//setting up a test in express-validator
var test = req.assert('access_token', 'required').notEmpty();
isValid(test, next);
//non error stuff
}
isValid = (tests, next) => {
//some more code here, that checks if any errors were found and save tem to the array errors.
if(errors.length > 0){
return next(new Error());
}
};
//a middleware that catches errors:
app.use((err, req, res, next) => {
res.json('error').end();
});
My problem with this is that it doesn't stop the propagation when I'm calling Next(new Error());, I could return true/false from isValid and then return next(new Error()), but that would add a lot of bloat to my controllers, is there some better way to do it from within the helper function?
In main route file, e.g. routes/index.js
// Set of func(req, res, next)
let v = require('validator'); // middleware-validators
let user = require('user'); // routes for user
...
app.get('/smth-route-of-user', v.isTokenSet, v.isEmail, ..., user.get)
In middlewares/validator.js
let v = require('validator-func-list');
...
exports.isTokenSet = function (req, res, next) {
if (v.isValid(req.body.token))
next(); // Forwarding to next middleware. In our route next() called v.isEmail
else
next(new Error('Token is empty')); // Stop route chain and call error-middleware;
}
exports.isEmail = function (req, res, next) {
...
You can join validators to one, e.g. checkUser(), and use only one in route.
In middlewares/errorHandler.js
module.exports = function (err, req, res, next) {
let msg = err.message; // Here we see 'Token is empty';
if (req.xhr)
res.json(msg);
else
res.render('error_page.html', {message: msg, ...});
// Here we can call next(err) to forwarding error to next errorHandler. In example below it was errorHandler2.
}
In app.js don't forget to attach error-middleware to application.
app.use(require('middlewares/errorHandler'));
app.use(require('middlewares/errorHandler2'));
If you need collect errors then validator must push error to req.errors (or another field as you want) and call next() without error. In render middleware you simple check req.errors.length and show normal or error page.
Code after isValid(test, next); always execute. Code below block it, but imho is dirty.
routingFunction = (req, res, next) {
var test = req.assert('access_token', 'required').notEmpty();
if (!isValid(test, next))
return; // callback called by isValid. It's dust.
//non error stuff
...
next(); // callback must be called
}
isValid = (tests, next) => {
if(errors.length > 0){
next(new Error());
return false;
}
return true;
};
More better use like this
routingFunction = (req, res, next) {
var test = req.assert('access_token', 'required').notEmpty();
if (!isValid(test))
return next (new Error('error description'));
//non error stuff
...
next();
}
I am currently working on formBuilder (client javascript <=> JSON <=> node), so i need effective way to handle JSON data on server. All forms are bind on one route, catched by middleware, so i need something like this:
Code is simplified (no regexs, req validators etc ..)
var middleware = require('../middleware'); // simple dir to object export
exports = module.exports =function(req,res,next) {
if(req.xhr && req.is('application/json')) {
var i, items = req.body.events.length;
for(i = 0; i < items; i++) {
var event = req.body.events[i];
if(middleware.forms[event] {
// -----------------
and here add that middleware into current flow ..
// -----------------
}
}
} else {
return next();
}
Easiest way is to prepare list of middleware, which will be used and call them in final route witch async .. but that i donw regard this as good way ..
So, i there any way to add requested middlwares to current flow, but before filan route ?
Middleware are just functions. So there is nothing wrong with just calling them. I had the same problem last week and I wrote a little helper.
var walkSubstack = function (stack, req, res, next) {
if (typeof stack === 'function') {
stack = [stack];
}
var walkStack = function (i, err) {
if (err) {
return next(err);
}
if (i >= stack.length) {
return next();
}
stack[i](req, res, walkStack.bind(null, i + 1));
};
walkStack(0);
};
You can use it with an array or just one function.
walkSubstack(middleware, req, res, next);
//or
walkSubstack([middleware, middleware], req, res, next);
I wrote something very similar:
let isActive1 = false;
let isActive2 = false;
let func1MD = (req, res, next) { /* ... */ }
let func2MD = (req, res, next) { /* ... */ }
let middleware = (function () {
// middleware #1
function func1(req, res, next) {
if (!isActive1) { return next(); }
return func1MD.call(null, req, res, next);
}
// middleware #2
function func2(req, res, next) {
if (!isActive2) { return next(); }
return func2MD.call(null, req, res, next);
}
// Returning an array of all middlewares to be called sequentially
return [
func1,
func2
]
})();
app.use(middleware);