So far, we write code to be executed in route function. Following the MVC Design Pattern, the route function is only used to call another callable object in the Controller section. Those callable objects are also called controller. So, we should create a controller to be called by the route function when a request is made through that route to conform with the MVC pattern.

 

//routes/index.js
import express from 'express'
const indexRoute = express.Router()

indexRoute.get('/',async (req,res,next) =>{
    const module = await import('../controller/getHome.js')
    module.default(req,res)
})

export default indexRoute

 

// controller/getHome.js

export default async (req,res)=>{
    res.send('ស្វាគមន៍​មក​កាន់​ទំព័រ​ដើម​!')
}

 

We should notice that as express route instance is a kind of middleware, it will automatically receive request, response, and next function as arguments for req, res, and next parameters respectively.

 

However, instead of directly sending response to the endpoint, we can define a controller to send data to the View section to insert that data into a template page and render it into an HTML page to be sent as the response to the request.

 

In Express.js, there is a variety of template engines to be used to render template file. Among which, EJS is a template engine using JavaScript as the template language to design template page, insert data and render it into HTML page. To use EJS template engine, we need to install EJS package.

 

npm install ejs

 

Next, we have to insert the code below into the entry point to set “view” folder as the folder to store template files, and EJS as the template engine for our application, and “static” as the folder to store static asset.

 

// index.js
// npm install express

import express from 'express'
const app = express()

const port = process.env.PORT || 8000

import mydb from './model/conMongoDB.js'
import indexRoute from './route/index.js'

app.use('/',async function(req,res,next){
    req.mydb = await mydb
    next()
})

import path from 'path'
const __dirname = path.resolve()
app.set('views', path.join(__dirname, 'view'))
app.set('view engine', 'ejs')
app.use(express.static(path.join(__dirname, 'static')))

app.use('/',indexRoute)

app.listen(port, () => {
  console.log(`This app is listening to the port ${port}`)
})

 

// controller/getHome.js

export default async (req,res)=>{
    const config = {
        siteTitle: 'Khmer Web Job',
        pageTitle: 'ទំព័រ​ដើម',
        message: 'ស្វាគមន៍​មក​កាន់​ទំព័រ​ដើម!'
    }

    res.render('base', {data:config})
}

 

<!--view/base.ejs-->
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8"/>
        <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
        <title><%= data.siteTitle %> | <%= data.pageTitle %></title>
        <link href="/images/siteLogo.png" rel="icon" ></link>
    </head>
    <body>
        <p><%= data.message %></p>
    </body>
</html>