Loading lessons...
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
- Import the
expressfunction module. - Instantiate the application instance (
const app = express()). - Define route endpoints (
app.get(),app.post()). - Bind to a port with
app.listen(port, callback).
TL;DR
express()creates an application instance.app.listen(port)starts the underlying HTTP server.