Quick Index
Goal


We'll improve on our first express app by adding a controller.

We want to organize our code into modules. We try to keep each module relatively small.

Example Steps


Create Project Directory
Create a project directory named "express-1b"
/express-1b
Add Project Sub-Directory
Within the project root dir, add a sub-dir named "controllers"
/express-1b/controllers
Initialize Project
Initialize the project normally.

🐞 gotcha - be sure to run this command from the project root dir (not a sub-dir).
>npm init
Install Packages
Use the npm install command to install the public packages http-status-codes and express

Note we install two packages here (we could also do this by running two commands).
>npm install http-status-codes express
Controller Code
We're going to code a home controller.

In the controllers subdir, create file home-controller.js.

Enter the code shown.

Note that we are simply moving the "homeFct" logic out of "main" and into the controller file.
const
	codes = require('http-status-codes'),
	br = '<br>';
	
const homeFct = (req, res) => {
	res.type('html')
	res.status(codes.OK);
	res.write('Greetings from web app' + br);
	res.write('Hello from controller');
	res.end();
};

exports.homeFct = homeFct;
Main Code
In the project root directory, create file main.js.

We are now importing the "home-controller" module and then getting the "homeFct" from it.
"use strict";

const
	port = 3000,
	express = require("express"),
	hc = require('./controllers/home-controller'),
	app = express(),
	msg = `Server started on port: ${port}`;
	
const started = () => console.log(msg);

//route path "/" to controller's "homeFct"
app.get("/", hc.homeFct);

//start the web server app
app.listen(port, started);
Run
Start the web server

Note: you very likely can setup a shortcut in your IDE to run the current file
>node main
Open Browser on URL
  • Open a web browser.
  • Go to the address bar
  • Enter "http://localhost:3000/" in the address bar
  • Or, you can click directly on the url shown here to the right


http://localhost:3000/

Greetings from web app
Hello from controller


Next


Next example...











Navigation