Express: How to create functions outside of app.get()?

766 views Asked by At

Something like this doesn't work for me:

function renderSite1() {
    return res.render('site.html');
}

app.get('/overview', function(req, res) {
    renderSite1();
}

How can I keep the routes clean and load function from outside?

2

There are 2 answers

0
mertselimb On

You can use it like this:

app.js

var campgroundRoutes      = require("./routes/campgrounds"),
    commentsRoutes        = require("./routes/comments"),
    indexRoutes            = require("./routes/index");

app.use(indexRoutes);
app.use("/campgrounds" , campgroundRoutes);
app.use("/campgrounds/:id/comments" , commentsRoutes);

index.js

var express = require("express");
var router = express.Router();

//------------------------------------------------------------------------------
//                               HOMEPAGE
//------------------------------------------------------------------------------

router.get("/" , function(req,res){
    res.render("landing");
});

module.exports = router;
0
Alexandru Olaru On

Id does not work because the scope of res, is the overview middleware, but render inherit the global scope which does not have the res declared.

What you can do is to pass req as parameter for renderSite1(), but this is not always clean.

What I enjoy to do is:

Create a function which returns a new function with the req fixed

function renderModule(res) { // it will be fixed for all the functions
   function renderSite1() {
     res.render() // visible
   }

   function renderSite2() {
     res.render() // visible
   }

   return {
     renderSite1,
     renderSite2
   }
}

This technique is called, revealing module pattern

What @artidokuz wrote in the answer is also a very good approach, divide your application using middlewares.