SyntaxStudy
Sign Up
Node.js Setting Up an Express Server
Node.js Beginner 9 min read

Setting Up an Express Server

Express is the most popular Node.js web framework. It adds routing, middleware support, and convenience methods on top of Node's built-in http module, making server development faster and cleaner.

Install Express with npm, then create an app.js file to define your server.

Example
// Install Express:
// npm install express

const express = require('express');
const app     = express();
const PORT    = process.env.PORT || 3000;

// Built-in middleware to parse JSON request bodies:
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

// Serve static files from the 'public' folder:
app.use(express.static('public'));

// Define routes:
app.get('/', (req, res) => {
    res.send('<h1>Welcome to Express!</h1>');
});

app.get('/api/status', (req, res) => {
    res.json({ status: 'running', uptime: process.uptime() });
});

app.post('/api/echo', (req, res) => {
    res.json({ received: req.body });
});

// 404 handler (must be after all routes):
app.use((req, res) => {
    res.status(404).json({ error: 'Route not found' });
});

// Start the server:
app.listen(PORT, () => {
    console.log(`Express server running on http://localhost:${PORT}`);
});