Web Scripting 3 - Node.js, Express, Middleware, and MySQL

Node.js Environment and Core HTTP Server

  • Project Initialization:

    • Initialize project and create package.json: npm init -y

    • Run scripts using Node: node app.js

  • Built-in http Module:

    • Imported via const http = require("http");

    • Server creation using http.createServer((req, res) => { ... }) where req represents the request object and res represents the response object.

    • Listen on a specified port: server.listen(PORT, () => { ... });

    • Response metadata configuration:

    • Set HTTP status code: res.statusCode = 200;

    • Set response headers: res.setHeader('Content-Type', 'text/html');

    • Complete response execution: res.end("Content");

Node.js HTTP Server Implementation
  • Hot Reloading Development Tool:

    • nodemon watches files for changes and automatically restarts the server.

    • Development dependency installation: npm install nodemon --save-dev

    • Execution command: npx nodemon app.js

Express.js Framework and Endpoint Routing

  • Framework Setup:

    • Install Express: npm install express --save

    • Import and initialize Express application:

    • const express = require('express');

    • const app = express();

    • app.listen(PORT, () => { ... });

  • HTTP Route Handlers (CRUD Operations):

    • app.get(path, (req, res) => { ... }): Read resources.

    • app.post(path, (req, res) => { ... }): Create new resources.

    • app.put(path, (req, res) => { ... }): Update existing resources.

    • app.delete(path, (req, res) => { ... }): Delete resources.

  • Dynamic URL Parameters:

    • Route paths use colon syntax for parameters (e.g., /reminders/:id).

    • Access parameter values via req.params.id and convert to numerical values using Number(req.params.id).

  • HTTP Status Codes:

    • 200: Success / OK.

    • 201: Created.

    • 404: Not Found.

    • 500: Internal Server Error.

  • API Testing Tool:

    • Postman is used to construct and transmit GET, POST, PUT, and DELETE requests.

Express Middleware and Modular Routing

  • Custom Middleware Functions:

    • Middleware functions accept (req, res, next) arguments.

    • Perform tasks prior to passing execution control down the stack by invoking next().

    • Allows attaching parsed variables directly to the request object (e.g., req.reminder = reqReminder).

  • Built-in JSON Parsing Middleware:

    • Mounted globally via app.use(express.json()); prior to route definitions.

    • Automatically parses JSON formatted request bodies and exposes the data on req.body.

  • Modular Route Management (express.Router):

    • Create router modules in a dedicated routes folder (e.g., routes/reminders.js, routes/users.js).

    • Router initialization: const router = express.Router();

    • Router export: module.exports = router;

    • Router mounting in app.js:

    • const remindersRouter = require('./routes/reminders');

    • app.use('/reminders', remindersRouter);

MySQL Database Integration with phpMyAdmin

  • Database and Access Administration:

    • Managed through phpMyAdmin via MAMP interface.

    • SQL command to create database:

    • CREATE DATABASE todo_app;

    • SQL command to create database user:

    • CREATE USER 'todo_app_user'@'localhost' IDENTIFIED BY '!k+Y2J';

    • SQL command to grant user privileges:

    • GRANT ALL PRIVILEGES ON todo_app.* TO 'todo_app_user'@'localhost' WITH GRANT OPTION;

    • SQL command to create data table:

    • CREATE TABLE todos ( id INT NOT NULL AUTO_INCREMENT, name VARCHAR(255) NOT NULL, body TEXT, due_date DATE NOT NULL, status INT(3) NOT NULL, PRIMARY KEY(id) );

  • Database Connection in Express:

    • Driver package installation: npm install mysql2 --save

    • Query execution method: connection.query(sqlStatement, (error, results) => { ... });

    • Returns status code 500 with the error message on query failure, or sends results as JSON upon success.


Here is a simple, stress-free breakdown of everything in your course so you can ace your 5-minute oral quiz!


1. The Big Picture (What are we building?)

Think of a restaurant:

  • Client / Browser / Postman: The customer asking for food.

  • Express Server (app.js): The kitchen receiving orders and sending food back.

  • MySQL Database: The pantry storing ingredients (data) permanently.


2. Core Concepts Made Simple
A. Node.js & NPM
  • Node.js: Allows JavaScript to run directly on a computer or server instead of inside a web browser.

  • npm init -y: Creates a package.json file, which is like a recipe list tracking installed software packages.

  • node app.js: Runs your backend server script.

B. Express.js Framework
  • Node has a basic built-in http module, but Express makes building web servers much easier and cleaner.

  • const app = express(): Initializes your Express server application.

  • app.listen(PORT): Tells your server to start listening for client requests on a specific port number (e.g., port 3000).

C. HTTP Methods (CRUD Operations)

Your server responds to actions sent from clients or Postman:

  • GET: Read data (e.g., fetch all reminders or fetch one reminder by ID via req.params.id).

  • POST: Create new data (reads new item info sent in req.body).

  • PUT: Update existing data by ID.

  • DELETE: Remove data by ID.

D. Middleware (app.use)
  • Middleware functions sit in the middle between receiving a request and sending a response.

  • app.use(express.json()): A built-in middleware that automatically parses incoming JSON body data into req.body so your code can easily read it.

  • Custom Middleware: Takes (req, res, next). Once its job is done, it calls next() to pass execution to the next function.

E. Modular Routing (express.Router)
  • Instead of putting every single route inside app.js, you move related routes into separate files inside a routes/ folder (like routes/reminders.js and routes/users.js).

  • You export the router with module.exports = router and mount it in app.js using app.use('/reminders', remindersRouter).

F. Database Integration (MySQL & phpMyAdmin)
  • phpMyAdmin: A visual tool to run SQL commands (like CREATE DATABASE todo_app; or CREATE TABLE todos (...)).

  • mysql2: An npm package that connects Express to MySQL.

  • connection.query(...): Runs SQL queries from Express. If it fails, it returns a 500 error status code; if it succeeds, it sends back query results as JSON.

G. Essential Tools & Status Codes
  • nodemon: A tool installed with npm install nodemon --save-dev that watches your code files and automatically restarts the server whenever you save changes.

  • Postman: A desktop application used to construct and test GET, POST, PUT, and DELETE requests before building a frontend UI.

  • Status Codes:

    • 200: Success / OK

    • 201: Created

    • 404: Not Found

    • 500: Internal Server Error