Express.js is a framework that makes writing Node.js web servers much easier. Splitting routes with the raw http module means more code, but with Express, app.get(), app.post(), and middleware let you manage everything effortlessly.
const express = require('express');
const app = express();
const port = 3000;
app.get('/', (req, res) => {
res.send('Hello from Express!');
});
app.get('/health', (req, res) => {
res.json({ status: 'ok', service: 'nodejs-tutorial' });
});
app.listen(port, () => {
console.log(`Express app running at http://localhost:${port}`);
});express() creates an Express app. app.get('/') is the home route, so when the browser visits the home path, it sends back text. The /health route is a small API endpoint that returns a JSON response.
Express app running at http://localhost:3000 GET /health result: { "status": "ok", "service": "nodejs-tutorial" }Info
Route order matters in Express. Put specific routes near the top, and keep fallback/404 routes at the very bottom.