Lesson 14 +10 XP

Creating Your First Express Server

Initializing an Express Application

Creating an Express server requires instantiating the app object and binding it to a network port.

// server.js
const express = require("express");
const app = express();

const PORT = process.env.PORT || 3000;

// Root endpoint route handler
app.get("/", (req, res) => {
  res.send("Hello from Express Server!");
});

// Health check endpoint
app.get("/health", (req, res) => {
  res.status(200).json({ status: "OK", timestamp: new Date() });
});

// Start listening for incoming network requests
app.listen(PORT, () => {
  console.log(`Server is running on http://localhost:${PORT}`);
});

Key Steps

  1. Import the express function module.
  2. Instantiate the application instance (const app = express()).
  3. Define route endpoints (app.get(), app.post()).
  4. Bind to a port with app.listen(port, callback).

TL;DR

  • express() creates an application instance.
  • app.listen(port) starts the underlying HTTP server.