DEV Community

avery
avery

Posted on

21. Express.js with Node.js

BootCamp by Dr.Angela

1. What is Express?

  • Express.js is a backend web framework for Node.js
  • Express vs Node.js
    • Node.js : Runtime environment (not a framework)
    • Express.js : Framework built on top of Node.js, Makes backend development easier
  • Why Express? : Less code, Better readability, Middleware support, Faster development
  • “It’s All Node To Me”
    • Can be used for : Web backend, IoT applications, Desktop apps (e.g. VS Code is built with Electron + Node)

2. Creating Your First Express Server

  • Backend structure
    • Server : computer running 24/7 (listening for requests)
    • Application : index.js (logic)
    • Database : data storage
  • Client-side vs Server-side
    • Client : browser
    • Server : backend system
  • Setup steps
    • mkdir project-folder
    • cd project-folder
    • touch index.js
    • npm init -y
    • npm i express
  • Basic server : ex) `import express from "express";

const app = express();
const port = 3000;

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

  • What is localhost? : Local server running on your computer
  • Check open ports
    • Windows : netstat -ano | findstr "LISTENING"
    • Mac/Linux : sudo lsof -i -P -n | grep LISTEN

3. HTTP Requests

  • HTTP : HyperText Transfer Protocol
  • HTTP Methods
    • GET : retrieve data
    • POST : send data
    • PUT : replace data
    • PATCH : update data
    • DELETE : remove data
  • Basic route : ex) app.get("/", (req, res) => {
    res.send("Hello, World!");
    });
  • Endpoints app.get("/about", (req, res) => {
    res.send("<h1>About Me</h1>");
    });
  • Nodemon : Auto-restarts server when changes are made
    • ex) npm i -g nodemon nodemon index.js

4. Postman

  • Tool for testing APIs (without frontend)
  • HTTP Status Codes
  • Install all dependencies : npm install
    • Installs everything listed in package.json

5. Introduction to Middleware

  • Body Parser : Handles form data (x-www-form-urlencoded)
    • app.use(bodyParser.urlencoded({extended:true}));
    • Express built-in middleware : app.use(express.urlencoded({ extended: true }));
  • Send file : res.sendFile(path);

6. Custom Middleware

  • What is middleware? : Code that runs between request and response
    • Used for : Logging, Authentication, Error handling, Data preprocessing
    • Example: Logger function logger(req, res, next) { console.log("Request Method:", req.method); console.log("Request URL:", req.url); next(); } app.use(logger);
  • Path utilities : ex) `import { dirname } from "path"; import { fileURLToPath } from "url";

const __dirname = dirname(fileURLToPath(import.meta.url));`

  • Important : Middleware order matters, body-parser must come before routes

7. Secrets Access Project

  • Example : `var userIsAuthorised = false;

function passwordCheck(req, res, next) {
const password = req.body["password"];

if (password === "ILoveProgramming") {
userIsAuthorised = true;
}

next();
}

app.use(passwordCheck);`

  • Route protection : `app.post("/check", (req, res) => { if (userIsAuthorised) { res.sendFile(dirname + "/public/secret.html"); } else { res.sendFile(dirname + "/public/index.html"); }

console.log(req.body);
});`

Top comments (0)