How to create express-routes using controllers


Express is a Nodejs frame work which can be used to create web applications. A route represents a page in the web app or website. An ideal express app consist of multiple web pages.

Prerequisites

We need the following before proceeding to the next step

  • Nodejs, install the Node
  • A Code editor of your choice ( sublimText/Atom/VS-Code)
  • A browser

For simple project we can put all of them inside a single file such as inex.js but it is a good practice to modularize the project with folder and files. So that it help manage the project easily.

The Folder structure

Following are the folder structure for the express project. First create project folder using command prompt or you can use the code editors command

In Atom you can use Shit +A for new folder , A for new file

Project Folder Structure
md express-route
cd express-route
md app
cd app
md controllers

Generate package file for the project with start script. We can use the npm init command for this purpose.

npm init -y 

by default init command will ask you a series of question , we can avoid them and use default values using the -y option.

Also add a start script to the pacjage.json file as follows

  "scripts": {
   "test": "echo \"Error: no test specified\" && exit 1",
   "start": "node index.js"
},

Create index,controller,routes files

Index.js : This file is the starting point of our project, create a new files with .js under the Project folder

controller.js : controllers hold the definition for the different routes ( Save under the controllers folder)

routes.js : This file where we declare all our express-routes and later use them in index.js (Save under the app folder)

Install the Express

Lets install essential packages for our project , on the shell please issue the following ( make sure you have internet connection)

npm install express --save

Define the controllers

The controller function is a simple java script module consisting of the following (in the file controllers.js)

module.exports = {
home:(req,res)=>{
  try {
    res.status(200).send('This is a Home Page')
  } catch (e) {
    console.log(e);
  }
},
about:(req,res)=>{
  try {
    res.status(200).send('This is a About Page')
  } catch (e) {
    console.log(e);
  }
},
contact:(req,res)=>{
  try {
    res.status(200).send('This is a Contact Page')
  } catch (e) {
    console.log(e);
  }
},
}

Prepare the routes

Let’s create our express-routes using the controller functions ( in the file app/routes.js )

const express = require('express');
const router = new express.Router;
const Controllers = require('./Controllers/Controllers')

router.get('/',Controllers.home)
router.get('/about',Controllers.about)
router.get('/contact',Controllers.contact)

module.exports = router;

Using express-router module we define the routes for our app and also import and utilized the controller functions and finally exported the module and get things ready for the routes in the index.js

Setup server, routes

The final step is to create use the routes and start our Node server (localhost). Now the index.js will look like

const express= require('express')
const app=express()
//routes
app.use(require('./app/routes'))

app.listen(3000, () => console.log('server on!'));

Here we had imported the routes.js as middle ware and will cause implementing all the routes defined in the routes.js file

Run the server

We can run the project using the start script configured in the package file.

npm start

and in the console the server on message will shown. Got to your browser and lunch the app using http://localhist:3000 and also try /about/ and /contact routes.