简体   繁体   中英

Separate express router params into different file

I've run into tad of a problem. I've currently got the shown below in my routing.js This is currently where I have both my .param and my .route I've separated the routes from the main app by creating a new router instance in my routing.js However I do not seem to be able to separate my params. Creating a new router instance in another file is useless seeing how the routes are router specific.

router.param("courseId", function(req, res, next, courseId){
Course.findById(courseId, function(err, course) {
    if(err)
        return next(err);
    else if(!course) {
        res.json({success: false, message: "No course found"});
        return next(new Error("No course found"));
    }
    req.course = course;
    next();
});

});

Any way I can separate the code above to another file, passing the router instance is something I've tried but I've most of the times gotten a stack error.

Any help appreciated!

Create params.js which looks like this

module.exports = function(router) {
    router.param(....);
}

and use it like this

var router = express.Router();
require ('params.js')(router);
// your other routes below
router.get(...);
//etc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM