Nairobi, Kenya

How to use controllers in node and express

How to use controllers in node and express Hey guys what’s up hoping that all is well. Today we are going to use controllers in building our REST API in node and express. We are going to build a server-less api and so there is no need of using a database

controllers

A controller contains functions of a particular route it controls how the requests are made to and fro the application In the rest-api application we made here we made all our functions in onside the route files but today we are going to separate the functions in a separate file.

Pre-requisites

  1. NodeJS
  2. Command Line
  3. Postman
  4. Code editor
Step one Navigate to one of your favorite folder using the command line and make a directory named node_controller Then navigate to the folder created
ian@IanoTech:~$ cd Documents/REACT
ian@IanoTech:~/Documents/REACT$ mkdir node_controller
ian@IanoTech:~/Documents/REACT$ cd node_controller
ian@IanoTech:~/Documents/REACT/node_controller$ 
Initialize your node app
npm init -y
ian@IanoTech:~/Documents/REACT/node_controller$ npm init -y
Wrote to /home/ian/Documents/REACT/node_controller/package.json:

{
  "name": "node_controller",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC"
}
Now lets make four files named
  • route.js
  • controller.js
  • server.js
  • data.json
ian@IanoTech:~/Documents/REACT/node_controller$ touch server.js
ian@IanoTech:~/Documents/REACT/node_controller$ touch data.json
ian@IanoTech:~/Documents/REACT/node_controller$ touch controller.js
ian@IanoTech:~/Documents/REACT/node_controller$ touch route.js

Data.json

This file will hold our data since we are not going to use a database we going to use simple json data for students information Using your favorite code editor open the folder created and then head over to data.json file In the data.json file add
[

{
	"id":"1",
	"name":"ian onyango",
	"admision":"CS0001017"
},
{
	"id":"2",
	"name":"Kate Wambui",
	"admision":"CS0451017"
},
{
	"id":"3",
	"name":"Kelly James",
	"admision":"CS03441017"
},
{
	"id":"4",
	"name":"Victoria Rame",
	"admision":"CS1241017"
},
{
	"id":"5",
	"name":"Roy Royega",
	"admision":"CS2131017"
}

]

Server.js

This file contains all our end points. first install express then import it in the file as shown below then define the port as 4000.
npm i express
add the lines of codes below
const express = require('express')
const app = express()


app.use(express.json())


const port =  4000
app.listen(port, ()=> console.log(`running on port ${port}`))

Controller.js

This file contains all the functions that the app is going to use it contains all the user defined functions and requests Import the data.json file as shown below
const students = require('./data')
Then define our getAll function to get all our data in json format then export the functions to be used
const students = require('./data')

const getAll = (req,res, next)=>{
	res.json(students)

}

module.exports ={ getAll}

routes.js

In this file we are only going to define our endpoint routes and methods first lets import the Router and express
const router = require('express').Router()
Then import our controller function
const studentsController = require('./controller')
Then define our route method as get for the function imported as shown
router.get('/students', studentsController.getAll)
Final file
const router = require('express').Router()
const studentsController = require('./controller')

router.get('/students', studentsController.getAll)

module.exports= router
import the route file in the server.js file the use it as a middle-ware as shown add these lines to server.js file
const studentsRoute = require('./route')

app.use('/', studentsRoute)
now run the application using the command node server.js and test using postman in the postman run localhost:4000/students to get all the data in the data.json file displayed
postman display image
Good our application is running well Lets get to the post method In the controller.js function add the lines below just after the getAll function
const newStudent =  (req,res,next)=>{
	const student = {
        id: students.length + 1,
        name : req.body.name,
        admision: req.body.admision
    };
    students.push(student)
    res.send(students)
}
First we must define new student as an object since we are taking many entities from it the req.body will take the input from our api then after we push the results then use the send method for the results to be visible on the postman interface after that we export the function just after the getAll function add newStudent function your file should look like this
const students = require('./data')

const getAll = (req,res, next)=>{
	res.json(students)

}
const newStudent =  (req,res,next)=>{
	const student = {
        id: students.length + 1,
        name : req.body.name,
        admision: req.body.admision
    };
    students.push(student)
    res.send(students)
}
module.exports ={ getAll, newStudent}
Then in our router.js file we only need one line of code this line of code will contain our method for our newStudent function and our route our method here is post and our route is ‘/new’
router.post('/new', studentsController.newStudent)
your final route.js file should look like this
const router = require('express').Router()
const studentsController = require('./controller')

router.get('/students', studentsController.getAll)
router.post('/new', studentsController.newStudent)


module.exports= router
Test your application on postman by adding new user using localhost:4000/new end point Use the name and admision fields only the id has already been taken care of
your final server.js file should look like
const express = require('express')
const app = express()
const studentsRoute = require('./route')


app.use(express.json())
app.use('/', studentsRoute)

const port =  4000

app.listen(port, ()=> console.log(`running on port ${port}`))
Thanks for making it up to this point.