node.js - NodeJs and ExpressJs Unable to separate the common code which is used in error and respose handling -


i'm new nodejs , expressjs. have following code, used list of users

in following code separate code in function(error, response, body) method , reuse in different method

how can this? using these repeatedly in methods separate , reuse in places.

router.get('/details/*******/all', function(req, res, next) {     var cookie = request.cookie("jsessionid=" + req.cookies.jsessionid);     jar.setcookie(cookie, list_of_staff, function(error, cookie) {});     request({         url: list_of_staff,         method: "get",         jar: jar,         headers: headers     }, function(error, response, body) {         if (!error && response.statuscode === 400 && !_.isundefined(body)) {             res.status(400)             res.json(body);         } else         if (!error && response.statuscode === 401 && !_.isundefined(body)) {             res.status(401)             res.json(body);         } else         if (!error && response.statuscode === 200 && !_.isundefined(body)) {             res.json(json.parse(body));         } else {             next(error);         }     }); }); 

you can move function place, give it's name. , can reuse it.

this example how it's can used:

router.get('/details/*******/all', function(req, res, next) {     var cookie = request.cookie("jsessionid=" + req.cookies.jsessionid);     jar.setcookie(cookie, list_of_staff, function(error, cookie) {});     request({         url: list_of_staff,         method: "get",         jar: jar,         headers: headers     }, newfunction.bind(null,res); });  function newfunction (res,error, response, body) {         // can use res (res.write)         if (!error && response.statuscode === 400 && !_.isundefined(body)) {             res.status(400)             res.json(body);         } else         if (!error && response.statuscode === 401 && !_.isundefined(body)) {             res.status(401)             res.json(body);         } else         if (!error && response.statuscode === 200 && !_.isundefined(body)) {             res.json(json.parse(body));         } else {             next(error);         }     } 

Comments

Popular posts from this blog

javascript - jQuery: Add class depending on URL in the best way -

caching - How to check if a url path exists in the service worker cache -

Redirect to a HTTPS version using .htaccess -