Express.js Cheat Sheet

Here’s a cheat sheet for Express.js:

Installation

# Install Express globally
npm install -g express

# Create a new Express app
express myapp

# Install dependencies
cd myapp
npm install

Basic Server Setup

const express = require('express');
const app = express();
const port = 3000;

app.listen(port, () => {
  console.log(`Server is running on port ${port}`);
});

Routing

// Handling GET requests
app.get('/', (req, res) => {
  res.send('Hello, World!');
});

// Handling POST requests
app.post('/api/data', (req, res) => {
  // Handle POST data
  res.send('Data received!');
});

Middleware

// Custom middleware
const myMiddleware = (req, res, next) => {
  // Your logic here
  next();
};

app.use(myMiddleware);

// Built-in middleware
app.use(express.json()); // Parse JSON in requests
app.use(express.urlencoded({ extended: true })); // Parse URL-encoded data

Route Parameters

// Using route parameters
app.get('/users/:id', (req, res) => {
  const userId = req.params.id;
  res.send(`User ID: ${userId}`);
});

Static Files

// Serving static files
app.use(express.static('public'));

Template Engines (Example: EJS)

# Install EJS
npm install ejs
// Set EJS as the view engine
app.set('view engine', 'ejs');

// Render EJS views
app.get('/profile', (req, res) => {
  res.render('profile', { username: 'JohnDoe' });
});

Error Handling

// Custom error handling middleware
app.use((err, req, res, next) => {
  console.error(err.stack);
  res.status(500).send('Something went wrong!');
});

Express Router

// Create a router
const router = express.Router();

// Use the router in your app
app.use('/api', router);

// Define routes in the router
router.get('/data', (req, res) => {
  res.json({ message: 'API data' });
});

Middleware Chain

// Middleware chain
app.use(middleware1);
app.use(middleware2);
app.use(middleware3);

Express Generator

# Install Express Generator
npm install -g express-generator

# Create a new app using the generator
express myapp
cd myapp
npm install
npm start

Additional Resources

This cheat sheet covers basic Express.js setup, routing, middleware, static files, template engines, error handling, Express Router, and more.