logo
eng-flag

Express.js Cheatsheet

Table of Contents

  1. Setup and Installation
  2. Basic Server
  3. Routing
  4. Middleware
  5. Request Object
  6. Response Object
  7. Static Files
  8. Template Engines
  9. Error Handling
  10. Database Integration

Setup and Installation

Installing Express

npm init -y
npm install express

Basic Server

Creating a Basic Server

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

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

app.listen(port, () => {
  console.log(`Server running at http://localhost:${port}`);
});

Routing

Basic Routing

app.get('/', (req, res) => {
  res.send('Home Page');
});

app.post('/submit', (req, res) => {
  res.send('Form Submitted');
});

app.put('/update', (req, res) => {
  res.send('Update Successful');
});

app.delete('/delete', (req, res) => {
  res.send('Delete Successful');
});

Route Parameters

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

Route Handlers

app.route('/book')
  .get((req, res) => {
    res.send('Get a book');
  })
  .post((req, res) => {
    res.send('Add a book');
  })
  .put((req, res) => {
    res.send('Update a book');
  });

Middleware

Application-level Middleware

app.use((req, res, next) => {
  console.log('Time:', Date.now());
  next();
});

Router-level Middleware

const router = express.Router();

router.use((req, res, next) => {
  console.log('Time:', Date.now());
  next();
});

app.use('/user', router);

Error-handling Middleware

app.use((err, req, res, next) => {
  console.error(err.stack);
  res.status(500).send('Something broke!');
});

Built-in Middleware

app.use(express.json()); // for parsing application/json
app.use(express.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded

Third-party Middleware

const morgan = require('morgan');
app.use(morgan('dev'));

Request Object

Request Properties

app.get('/user', (req, res) => {
  console.log(req.method);    // GET
  console.log(req.path);      // /user
  console.log(req.headers);   // request headers
  console.log(req.query);     // query string parameters
  console.log(req.body);      // body of the request (requires body-parser)
});

Response Object

Response Methods

app.get('/example', (req, res) => {
  res.status(200);                   // Set status
  res.set('Content-Type', 'text/plain');  // Set headers
  res.send('Hello World');           // Send response
  res.json({ user: 'John Doe' });    // Send JSON response
  res.download('/path/to/file');     // Send file as an attachment
  res.redirect('/another-page');     // Redirect
  res.render('index', { title: 'Home' }); // Render view
});

Static Files

Serving Static Files

app.use(express.static('public'));

Template Engines

Setting up EJS

app.set('view engine', 'ejs');

app.get('/', (req, res) => {
  res.render('index', { title: 'Home' });
});

Error Handling

404 Handler

app.use((req, res, next) => {
  res.status(404).send("Sorry, can't find that!");
});

Error Handler

app.use((err, req, res, next) => {
  console.error(err.stack);
  res.status(500).send('Something broke!');
});

Database Integration

MongoDB with Mongoose

const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/myapp', { useNewUrlParser: true, useUnifiedTopology: true });

const User = mongoose.model('User', { name: String, email: String });

app.post('/users', async (req, res) => {
  const user = new User(req.body);
  await user.save();
  res.send(user);
});

SQL with Sequelize

const { Sequelize, DataTypes } = require('sequelize');
const sequelize = new Sequelize('database', 'username', 'password', {
  host: 'localhost',
  dialect: 'mysql'
});

const User = sequelize.define('User', {
  name: DataTypes.STRING,
  email: DataTypes.STRING
});

app.post('/users', async (req, res) => {
  const user = await User.create(req.body);
  res.send(user);
});

2024 © All rights reserved - buraxta.com