📚

Express.js Crash Course Notes

Jun 22, 2024

Express.js Crash Course

Introduction

  • Revamped Course: Update of a 5-year-old Express.js course
  • Node.js Crash Course: Revamped version available; recommended to watch first for newcomers

What is Express.js?

  • Description: Minimal, flexible Node.js web framework
  • Use Cases: Server-side applications, APIs, microservices
  • Popularity: The go-to framework for Node.js; widely used by companies like IBM, Uber, Nike
  • Comparison: Mongoose DB, Express, React, Node.js (MERN stack). Also MEVN (with Vue.js) or MEAN (with Angular).

Features of Express

  • Simplifies HTTP Requests: Provides tools to build APIs easily
  • Speed and Flexibility: Fast, unopinionated framework allowing freedom in structure and libraries
  • Opinionated vs. Unopinionated Frameworks: Examples include Ruby on Rails (Opinionated) vs. Express (Unopinionated)

Prerequisites

  • JavaScript Fundamentals: Includes ES6, arrow functions, destructuring, promises, async/await
  • Node.js Basics: Basic understanding and familiarity with npm, installing packages, JSON data

Course Outline

  • Set Up Server: Creating routes, handling requests
  • Middleware: Custom logging, error handling middleware
  • CRUD Operations: Create, Read, Update, Delete (Create full CRUD API)
  • Template Engines: Example using embedded JavaScript like ejs
  • Error Handling, Third-Party Packages, Controllers: Fetching data from frontend, using environment variables

Getting Started

  1. Set Up Project: VSCode, install Express via npm
  2. Create Server.js: Initialize Express and set up server
  3. Create Routes: Add routes for different purposes (GET, POST)
  4. Serve HTML Files: Using res.sendFile, Express static middleware
  5. Handle JSON Data: Use res.json to send JSON data, deal with databases

Middleware

  • Body Parsers: express.json for raw JSON, express.urlencoded for form data
  • Custom Middleware: Demonstration of custom logging middleware

Error Handling

  • Handler Setup: Create middleware for custom error responses
  • Custom Response: Set various status codes, handle non-existing routes (404s)

Controller Methods

  • Separation of Concerns: Use controllers for cleaner, manageable code
  • Import and Configure

Frontend Interaction

  1. Basic Setup: HTML form and Fetch API
  2. Add Frontend JS: Fetch and post data via API endpoints

Template Engine: EJS

  • Setup EJS: Configuring and rendering EJS templates
  • Dynamic Data: Pass variables to EJS for rendering
  • Partials and Layouts: Use partials for reusable components like headers

Conclusion

  • Many techniques to make development easier
  • Express allows high flexibility and customization

Note: For detailed steps and code, refer to the actual Project setup explained above.