🖥️

Node.js and Express Fundamentals

Jul 21, 2024

Node.js and Express Fundamental Course by John Smilga

Course Overview

  • Comprehensive 8-hour tutorial on Node.js and Express.js.
  • Focus on building backend and full stack web apps with JavaScript.
  • Hands-on projects for practical learning.

Series Outline

  1. Node.js and Express Fundamentals
    • Introduction to Node.js and Express.js
    • Basic setup and development environment
    • Overview of REST API with Express.js
    • Full-blown MERN application
  2. Additional Technologies
    • MongoDB
    • Mongoose

Learning Approach

  • Project-based learning with step-by-step instructions.
  • Deployment steps for project completion.

Introduction to Node.js

  • Definition: Environment to run JavaScript outside of the browser.
  • History: Created in 2009, built on Chrome's V8 JavaScript engine.
  • Community: Large, active Node.js community for support and resources.
  • Language Uniformity: Full stack development with JavaScript.
  • Course Requirements: Basic HTML, CSS, and JavaScript (ES6).

Course Structure

  1. Section 1: Node.js Fundamentals
    • Introduction to Node.js
    • Setting up development environment
  2. Section 2: Node.js vs Browser JavaScript
    • Differences in APIs and functionalities
  3. Section 3: Express.js Fundamentals
    • Introduction to Express.js
    • Setting up basic Express server
    • Building REST APIs
  4. Practical Applications
    • Building a complex Node.js app
    • Deploying applications

Node.js Overview

  • Node.js in Simplicity: Uses Chrome's V8 engine, runs JS outside the browser.
  • Advantages: Large community, same language for front-end and back-end.
  • Course Requirements: Familiarity with HTML, CSS, and modern JS features (ES6).

Code Summary: Simple Node.js Server

const http = require('http'); const server = http.createServer((req, res) => { if(req.url === '/'){ res.write('<h1>Home Page</h1>'); res.end(); } else if(req.url === '/about') { res.write('<h1>About Page</h1>'); res.end(); } else { res.write('<h1>404 - Page not found</h1>'); res.end(); } }); server.listen(5000);

Express.js Overview

  • Benefits: Simplifies server-side code
  • Express Server Setup const express = require('express'); const app = express(); app.get('/', (req, res) => { res.send('<h1>Home Page</h1>'); }); app.get('/about', (req, res) => { res.send('<h1>About Page</h1>'); }); app.all('*', (req, res) => { res.status(404).send('<h1>404 Page not found</h1>'); }); app.listen(5000, () => { console.log('Server is listening on port 5000...'); }); ``*

Static Assets with Express

  1. Definition and Example
app.use(express.static('./public'));

Middleware in Express.js

  • Types: Built-in, third-party, custom
  • Example Logger Middleware
const logger = (req, res, next) => { console.log(`${req.method} ${req.url}`); next(); }; app.use(logger);

Handling Errors: Necessary Middleware

  1. Error Middleware
app.use((err, req, res, next) => { console.error(err.stack); res.status(500).send('Something broke!'); });

Essential Middleware for Handling JSON Payloads

  • express.json() and express.urlencoded({ extended: false }).

CRUD Operations in Express.js

  1. Create (POST) app.post('/api/people', (req, res) => { const { name } = req.body; if (!name) { return res.status(400).json({ success: false, msg: 'Please provide name value' }); } res.status(201).send({ success: true, person: name });

});

2. **Read** (GET) ```javascript app.get('/api/people', (req, res) => { res.status(200).json({ success: true, data: people }); });
  1. Update (PUT) app.put('/api/people/:id', (req, res) => { const { id } = req.params; const { name } = req.body; const person = people.find((person) => person.id === Number(id)); if (!person) { return res.status(404).json({ success: false, msg: `No person with id ${id}` }); } else { const newPeople = people.map((person) => { if (person.id === Number(id)) { person.name = name; } return person; }); res.status(200).json({ success: true, data: newPeople }); }

});

4. **Delete** (DELETE) ```javascript app.delete('/api/people/:id', (req, res) => { const { id } = req.params; const person = people.find((person) => person.id === Number(id)); if (!person) { return res.status(404).json({ success: false, msg: `No person with id ${id} `}); } const newPeople = people.filter((person) => person.id !== Number(id)); return res.status(200).json({ success: true, data: newPeople }); });

Using Postman for Testing APIs

  1. Setup
    • Download and install Postman from postman.com
    • Create requests and add the URL.
  2. Example GET Request
  3. Example POST Request (to add a new person)
  4. Other Methods (PUT, DELETE) - Similar setup with relevant body and URL parameters.

Organizing Code in Express

  1. Using Routers

    • Create a router for each module (e.g., routes/people.js)
    const express = require('express'); const router = express.Router(); router.get('/', (req, res) => ...); // Export the router module.exports = router;
  2. Controllers: Separate business logic from routes.

    • controllers/people.js
    const getPeople = (req, res) => { res.status(200).json({ success: true, data: people }); }; // Export controllers module.exports = { getPeople };