We need to create a basic Express.js web server that:
Input:
Output:
Requirements:
Let's break this down into manageable steps:
Basic Solution:
// Step 1: Create project structure
mkdir server
cd server
npm init -y
// Step 2: Install dependencies
npm install express
npm install -D nodemon
// Step 3-6: Create app.js
const express = require('express');
const app = express(); // Initialize Express application
// Define port
const port = 5000;
// Create route handler for /status
app.get('/status', (req, res) => {
res.send('The server is alive!');
});
// Start server
app.listen(port, () => {
console.log(`Server is listening on port ${port}`);
});
Package.json scripts:
{
"scripts": {
"start": "node app.js",
"dev": "nodemon app.js"
}
}
Here's a more structured version with error handling and environment variables:
// Load environment variables
require('dotenv').config();
const express = require('express');
const app = express();
// Environment variables with fallback
const port = process.env.PORT || 5000;
// Basic error handling middleware
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).send('Something broke!');
});
// Health check route
app.get('/status', (req, res) => {
try {
res.send('The server is alive!');
} catch (error) {
next(error);
}
});
// Graceful server startup
const startServer = async () => {
try {
app.listen(port, () => {
console.log(`Server is listening on port ${port}`);
});
} catch (error) {
console.error('Failed to start server:', error);
process.exit(1);
}
};
startServer();
Let's examine the key concepts:
Think of Express as a traffic controller at a busy intersection. When we call express(), we're essentially creating our traffic controller who will direct incoming requests (traffic) to the right destinations (route handlers).
Route handlers are like receptionists in a building. When someone (a request) arrives at a specific entrance (/status), the receptionist (route handler) provides a specific response ("The server is alive!").
The app.listen() function is like opening the doors of a store for business. The port number (5000) is like the store's street address - it tells clients where to find our server.
The two npm scripts are like having two different modes of operation:
This basic Express setup is similar to how many real-world applications begin:
To deepen your understanding, try these extensions: