Create a Web Server

Learning Objectives

Section 26.1: Using a Framework

Express.js

const express = require("express");
const app = express();

// Middleware
app.use(express.json());
app.use(express.static("public"));

// Routes
app.get("/", (req, res) => {
    res.send("Hello from Express!");
});

// Start server
app.listen(3000, () => {
    console.log("Server running on port 3000");
});

Installing Express

npm init -y
npm install express

Section 26.2: Responding to Requests

GET Requests

// Simple response
app.get("/", (req, res) => {
    res.send("Hello!");
});

// Respond with HTML
app.get("/page", (req, res) => {
    res.send("<h1>Welcome</h1>");
});

// Respond with JSON
app.get("/api/data", (req, res) => {
    res.json({ message: "Success", data: [1, 2, 3] });
});

// URL parameters
app.get("/users/:id", (req, res) => {
    let userId = req.params.id;
    res.json({ id: userId, name: "User" + userId });
});

// Query parameters
app.get("/search", (req, res) => {
    let query = req.query.q;
    res.json({ search: query });
});

Section 26.3: Creating an API

REST API with Express

const express = require("express");
const app = express();
app.use(express.json());

let products = [
    { id: 1, name: "Product A", price: 19.99 },
    { id: 2, name: "Product B", price: 29.99 }
];

// GET all products
app.get("/api/products", (req, res) => {
    res.json(products);
});

// GET single product
app.get("/api/products/:id", (req, res) => {
    let product = products.find(p => p.id == req.params.id);
    if (product) {
        res.json(product);
    } else {
        res.status(404).json({ error: "Product not found" });
    }
});

// CREATE product
app.post("/api/products", (req, res) => {
    let newProduct = {
        id: products.length + 1,
        name: req.body.name,
        price: req.body.price
    };
    products.push(newProduct);
    res.status(201).json(newProduct);
});

// UPDATE product
app.put("/api/products/:id", (req, res) => {
    let product = products.find(p => p.id == req.params.id);
    if (product) {
        product.name = req.body.name;
        product.price = req.body.price;
        res.json(product);
    } else {
        res.status(404).json({ error: "Product not found" });
    }
});

// DELETE product
app.delete("/api/products/:id", (req, res) => {
    let index = products.findIndex(p => p.id == req.params.id);
    if (index !== -1) {
        let deleted = products.splice(index, 1);
        res.json(deleted[0]);
    } else {
        res.status(404).json({ error: "Product not found" });
    }
});

app.listen(3000, () => {
    console.log("API running on http://localhost:3000");
});

Section 26.4: Exposing Data

Database Integration (Example with array)

const express = require("express");
const app = express();
app.use(express.json());

// Simulate database
const users = [
    { id: 1, name: "Alice", email: "alice@example.com" },
    { id: 2, name: "Bob", email: "bob@example.com" }
];

app.get("/api/users", (req, res) => {
    res.json(users);
});

app.get("/api/users/:id", (req, res) => {
    let user = users.find(u => u.id == req.params.id);
    res.json(user || { error: "Not found" });
});

Section 26.5: Accepting Data

Handling Form Data and JSON

const express = require("express");
const app = express();

// Parse JSON
app.use(express.json());

// Parse form data
app.use(express.urlencoded({ extended: true }));

app.post("/api/contact", (req, res) => {
    let { name, email, message } = req.body;
    
    if (!name || !email || !message) {
        return res.status(400).json({ error: "Missing fields" });
    }
    
    // Process submission
    console.log("New contact:", { name, email, message });
    
    res.json({ success: true, message: "Message received" });
});

app.listen(3000);

Section 26.6: Publishing Web Pages

Serving Static Files

const express = require("express");
const app = express();

// Serve files from public folder
app.use(express.static("public"));

// That's it! Now index.html, css, js, images in public/ are served

Directory Structure

project/
├── server.js
├── public/
│   ├── index.html
│   ├── style.css
│   └── script.js
└── package.json

Key Takeaways

✅ Express.js simplifies server creation
✅ Routes handle different URLs
✅ REST APIs use HTTP methods
✅ Middleware processes requests
✅ Static files served from folder
✅ JSON responses for APIs

Quiz Questions


Next Module: Module 27 - Project 3: A Notetaking Web App