BAB 3: Express.js Framework

BAB 3: Express.js Framework

3.1 Pengenalan Express.js

3.1.1 Apa itu Express.js?

Express.js adalah web framework yang minimalis dan fleksibel untuk Node.js. Framework ini menyediakan berbagai fitur untuk membangun aplikasi web dan API.

3.1.2 Instalasi Express.js

# Membuat project baru
mkdir express-app
cd express-app
npm init -y

# Install Express
npm install express

# Install dependencies umum
npm install cors dotenv morgan

3.1.3 Aplikasi Express Dasar

// app.js
const express = require('express');
const cors = require('cors');
const morgan = require('morgan');
require('dotenv').config();

const app = express();

// Middleware
app.use(cors());
app.use(morgan('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

// Route dasar
app.get('/', (req, res) => {
  res.json({ message: 'Welcome to Express API' });
});

// Start server
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`);
});

3.2 Routing

3.2.1 Basic Routing

// routes/index.js
const express = require('express');
const router = express.Router();

// GET method
router.get('/', (req, res) => {
  res.json({ message: 'GET request' });
});

// POST method
router.post('/', (req, res) => {
  res.json({ message: 'POST request' });
});

// PUT method
router.put('/:id', (req, res) => {
  res.json({ message: `PUT request for id ${req.params.id}` });
});

// DELETE method
router.delete('/:id', (req, res) => {
  res.json({ message: `DELETE request for id ${req.params.id}` });
});

module.exports = router;

3.2.2 Route Parameters

// routes/users.js
const router = express.Router();

// Route dengan parameter
router.get('/users/:id', (req, res) => {
  const { id } = req.params;
  res.json({ userId: id });
});

// Multiple parameters
router.get('/users/:userId/posts/:postId', (req, res) => {
  const { userId, postId } = req.params;
  res.json({ userId, postId });
});

// Optional parameters
router.get('/products/:category?', (req, res) => {
  const { category } = req.params;
  res.json({ category: category || 'all' });
});

3.2.3 Query Strings

// routes/products.js
router.get('/search', (req, res) => {
  const { q, limit = 10, page = 1 } = req.query;
  res.json({
    search: q,
    limit: parseInt(limit),
    page: parseInt(page)
  });
});

3.3 Middleware

3.3.1 Built-in Middleware

// app.js
const express = require('express');
const app = express();

// JSON parsing middleware
app.use(express.json());

// URL-encoded parsing middleware
app.use(express.urlencoded({ extended: true }));

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

3.3.2 Custom Middleware

// middleware/logger.js
const logger = (req, res, next) => {
  console.log(`${req.method} ${req.path} - ${new Date().toISOString()}`);
  next();
};

// middleware/auth.js
const auth = (req, res, next) => {
  const token = req.headers.authorization;
  
  if (!token) {
    return res.status(401).json({ message: 'No token provided' });
  }
  
  // Verify token logic here
  next();
};

// Menggunakan middleware
app.use(logger);
app.use('/api', auth);

3.3.3 Error Handling Middleware

// middleware/error.js
const errorHandler = (err, req, res, next) => {
  console.error(err.stack);
  
  const status = err.status || 500;
  const message = err.message || 'Something went wrong!';
  
  res.status(status).json({
    status: 'error',
    message
  });
};

// Custom error class
class AppError extends Error {
  constructor(message, status) {
    super(message);
    this.status = status;
  }
}

// Menggunakan error handler
app.use(errorHandler);

3.4 Request & Response

3.4.1 Request Object

router.post('/example', (req, res) => {
  // Request body
  console.log(req.body);
  
  // URL parameters
  console.log(req.params);
  
  // Query string
  console.log(req.query);
  
  // Headers
  console.log(req.headers);
  
  // Cookies
  console.log(req.cookies);
  
  // Files (dengan multer)
  console.log(req.file);
});

3.4.2 Response Object

router.get('/examples', (req, res) => {
  // Send JSON response
  res.json({ message: 'Success' });
  
  // Send status
  res.sendStatus(200);
  
  // Send status with data
  res.status(201).json({ message: 'Created' });
  
  // Send file
  res.sendFile('/path/to/file.pdf');
  
  // Redirect
  res.redirect('/new-path');
  
  // Set cookie
  res.cookie('token', 'value', { httpOnly: true });
  
  // Clear cookie
  res.clearCookie('token');
});

3.5 File Upload

3.5.1 Setup Multer

const multer = require('multer');

// Konfigurasi storage
const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, 'uploads/');
  },
  filename: (req, file, cb) => {
    const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
    cb(null, file.fieldname + '-' + uniqueSuffix + path.extname(file.originalname));
  }
});

// Filter file
const fileFilter = (req, file, cb) => {
  if (file.mimetype.startsWith('image/')) {
    cb(null, true);
  } else {
    cb(new Error('Not an image!'), false);
  }
};

const upload = multer({ 
  storage: storage,
  fileFilter: fileFilter,
  limits: {
    fileSize: 1024 * 1024 * 5 // 5MB
  }
});

3.5.2 Implementasi Upload

// Single file upload
router.post('/upload', upload.single('image'), (req, res) => {
  if (!req.file) {
    return res.status(400).json({ message: 'Please upload a file' });
  }
  
  res.json({
    message: 'File uploaded successfully',
    file: req.file
  });
});

// Multiple files upload
router.post('/upload-many', upload.array('images', 5), (req, res) => {
  if (!req.files.length) {
    return res.status(400).json({ message: 'Please upload files' });
  }
  
  res.json({
    message: 'Files uploaded successfully',
    files: req.files
  });
});

3.6 Template Engines

3.6.1 Setup EJS

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

// Set view engine
app.set('view engine', 'ejs');
app.set('views', './views');

// Route dengan template
app.get('/page', (req, res) => {
  res.render('index', {
    title: 'My Page',
    message: 'Welcome to Express'
  });
});

3.6.2 Contoh Template EJS

<!-- views/index.ejs -->
<!DOCTYPE html>
<html>
<head>
  <title><%= title %></title>
</head>
<body>
  <h1><%= message %></h1>
  
  <% if (user) { %>
    <p>Welcome, <%= user.name %></p>
  <% } %>
  
  <ul>
    <% items.forEach(function(item) { %>
      <li><%= item.name %></li>
    <% }); %>
  </ul>
</body>
</html>

Latihan

  1. Buat REST API sederhana dengan Express

  2. Implementasi sistem file upload

  3. Buat custom middleware untuk logging dan authentication

  4. Implementasi error handling

  5. Buat halaman dengan template engine

Review

  • Express.js menyediakan framework yang fleksibel untuk Node.js

  • Routing memungkinkan penanganan berbagai HTTP request

  • Middleware adalah kunci untuk memproses request

  • Error handling yang baik penting untuk reliability

  • Template engine memungkinkan rendering dynamic HTML

Last updated