Konsep HTTP: Request dan Response pada Express.js - Perwira Learning Center



1. Latar Belakang

    Oke, hari ini saya akan membahas Konsep HTTP: Request dan Response. Ini adalah konsep paling penting dalam pengembangan web! Ibarat kita mau pesan makanan via GoFood:

  • Request = Kita pesan nasi goreng via aplikasi
  • Response = Driver ngantar nasi gorengnya ke rumah

HTTP adalah "bahasa" yang dipakai browser dan server untuk ngobrol. Tanpa paham HTTP, kita gak bisa bikin web yang benar!

2. Alat dan Bahan

a. Perangkat Lunak

  1. Express.js Project yang sudah kita buat kemarin
  2. Browser (Chrome/Firefox) - Untuk testing
  3. Postman - Untuk simulasi request yang lebih kompleks
  4. Developer Tools Browser - Untuk lihat detail HTTP
  5. Terminal/CMD - Untuk jalanin server

b. Perangkat Keras

  1. Laptop/PC yang sama dengan sebelumnya

3. Pembahasan

3.1 Apa itu HTTP?

HTTP (HyperText Transfer Protocol) = Protokol untuk kirim-terima data di web.

Analogi Simple:

  • HTTP Request = Surat permintaan
  • HTTP Response = Surat balasan
  • Server = Kantor yang terima surat
  • Client = Orang yang kirim surat
javascript
// Contoh nyata di kehidupan:
// CLIENT: "Halo, saya mau beli nasi goreng 2 porsi" ← REQUEST
// SERVER: "Oke, total Rp 40.000. Silakan bayar" ← RESPONSE

3.2 Komponen HTTP Request

Setiap request punya 3 bagian utama:

1. Request Line

http
GET /api/users HTTP/1.1
  • Method: GET (apa yang mau dilakukan)
  • Path: /api/users (alamat tujuan)
  • Version: HTTP/1.1 (versi HTTP)

2. Headers

http
Host: localhost:3000
User-Agent: Chrome/120.0
Content-Type: application/json
Authorization: Bearer token123
  • Informasi tambahan tentang request
  • Seperti amplop surat (siapa pengirim, penting/tidak, dll)

3. Body (Opsional)

json
{
  "name": "Andi",
  "email": "andi@email.com"
}
  • Data yang dikirim (untuk POST, PUT)
  • Kalo GET biasanya kosong

3.3 HTTP Methods (GET, POST, PUT, DELETE)

Ini yang kita pakai di Express:

javascript
// GET - Minta data (baca)
app.get('/users', (req, res) => {
  // Minta data users
});

// POST - Kirim data baru (buat)
app.post('/users', (req, res) => {
  // Buat user baru
});

// PUT - Update data (ubah)
app.put('/users/:id', (req, res) => {
  // Update user berdasarkan ID
});

// DELETE - Hapus data
app.delete('/users/:id', (req, res) => {
  // Hapus user
});

Analogi Restoran:

  • GET = Lihat menu
  • POST = Pesan makanan
  • PUT = Ubah pesanan
  • DELETE = Batalkan pesanan

3.4 HTTP Status Codes

Kode angka yang kasih tahu hasil request:

1xx: Informational

  • 100 Continue = "Oke lanjutin"

2xx: Success ✅

javascript
res.status(200).json({ message: "Success!" });
  • 200 OK = Semua berhasil
  • 201 Created = Data berhasil dibuat
  • 204 No Content = Berhasil tapi tanpa data

3xx: Redirection

  • 301 Moved Permanently = Pindah alamat permanen
  • 302 Found = Pindah sementara

4xx: Client Error ❌

javascript
res.status(404).json({ error: "Not found" });
  • 400 Bad Request = Request-nya salah format
  • 401 Unauthorized = Belum login
  • 403 Forbidden = Gak boleh akses
  • 404 Not Found = Halaman/data tidak ditemukan

5xx: Server Error 🚨

javascript
res.status(500).json({ error: "Server error" });
  • 500 Internal Server Error = Server error
  • 503 Service Unavailable = Server lagi maintenance

3.5 Praktik: Membuat Server dengan Berbagai Response

Buat file http-practice.js:

javascript
const express = require('express');
const app = express();
const PORT = 3001; // Pakai port berbeda dari sebelumnya

// Middleware untuk parsing JSON
app.use(express.json());

// ==================== CONTOH RESPONSE BERBEDA ====================

// 1. Response TEXT biasa
app.get('/hello', (req, res) => {
  res.send('Halo! Ini response text biasa.');
});

// 2. Response HTML
app.get('/html', (req, res) => {
  res.send(`
    <!DOCTYPE html>
    <html>
    <head>
      <title>Response HTML</title>
      <style>
        body { font-family: Arial; padding: 20px; }
        .success { color: green; }
        .error { color: red; }
      </style>
    </head>
    <body>
      <h1>Contoh Response HTML</h1>
      <p class="success">✅ Request berhasil!</p>
      <p>Waktu server: ${new Date().toLocaleString()}</p>
      <a href="/hello">← Ke hello text</a>
    </body>
    </html>
  `);
});

// 3. Response JSON (paling sering dipakai di API)
app.get('/api/user', (req, res) => {
  res.json({
    success: true,
    message: "Data user berhasil diambil",
    data: {
      id: 1,
      name: "Andi Pratama",
      email: "andi@email.com",
      age: 25,
      isActive: true
    },
    metadata: {
      timestamp: new Date().toISOString(),
      version: "1.0"
    }
  });
});

// 4. Response dengan status code berbeda
app.get('/api/status/:code', (req, res) => {
  const code = parseInt(req.params.code);
  
  switch(code) {
    case 200:
      res.status(200).json({ 
        status: 200, 
        message: "✅ Success! Semua berjalan lancar." 
      });
      break;
      
    case 400:
      res.status(400).json({ 
        status: 400, 
        error: "❌ Bad Request",
        message: "Format request salah. Cek lagi datanya."
      });
      break;
      
    case 404:
      res.status(404).json({ 
        status: 404, 
        error: "🔍 Not Found",
        message: "Data yang kamu cari tidak ditemukan."
      });
      break;
      
    case 500:
      res.status(500).json({ 
        status: 500, 
        error: "🚨 Server Error",
        message: "Ada masalah di server kita. Coba lagi nanti."
      });
      break;
      
    default:
      res.status(400).json({ 
        error: "Status code tidak valid",
        validCodes: [200, 400, 404, 500]
      });
  }
});

// 5. Response redirect
app.get('/old-page', (req, res) => {
  res.redirect('/html');
});

// 6. Response file (static)
app.get('/download', (req, res) => {
  res.download('README.md'); // Akan download file README.md
});

// 7. POST Request dengan body data
app.post('/api/login', (req, res) => {
  const { username, password } = req.body;
  
  // Validasi sederhana
  if (!username || !password) {
    return res.status(400).json({
      success: false,
      error: "Username dan password wajib diisi"
    });
  }
  
  // Simulasi cek login
  if (username === "admin" && password === "12345") {
    res.status(200).json({
      success: true,
      message: "Login berhasil!",
      token: "jwt_token_simulation_123",
      user: {
        username: "admin",
        role: "administrator"
      }
    });
  } else {
    res.status(401).json({
      success: false,
      error: "Login gagal",
      message: "Username atau password salah"
    });
  }
});

// 8. PUT Request untuk update
app.put('/api/users/:id', (req, res) => {
  const userId = req.params.id;
  const updateData = req.body;
  
  res.status(200).json({
    success: true,
    message: `User dengan ID ${userId} berhasil diupdate`,
    data: updateData,
    updatedAt: new Date().toISOString()
  });
});

// 9. DELETE Request
app.delete('/api/users/:id', (req, res) => {
  const userId = req.params.id;
  
  res.status(200).json({
    success: true,
    message: `User dengan ID ${userId} berhasil dihapus`,
    deletedAt: new Date().toISOString()
  });
});

// 10. Error handling
app.get('/simulate-error', (req, res) => {
  // Simulasi error
  throw new Error("Ini error simulasi!");
});

// Error handler middleware
app.use((err, req, res, next) => {
  console.error("🔥 Error terjadi:", err.message);
  res.status(500).json({
    success: false,
    error: "Internal Server Error",
    message: process.env.NODE_ENV === 'development' 
      ? err.message 
      : "Terjadi kesalahan di server"
  });
});

// 404 Handler
app.use((req, res) => {
  res.status(404).json({
    success: false,
    error: "Not Found",
    message: `Route ${req.method} ${req.url} tidak ditemukan`
  });
});

// ==================== JALANKAN SERVER ====================
app.listen(PORT, () => {
  console.log("🌐 HTTP PRACTICE SERVER");
  console.log("=".repeat(40));
  console.log(`Server jalan di: http://localhost:${PORT}`);
  console.log("");
  console.log("📡 ENDPOINT YANG TERSEDIA:");
  console.log("");
  console.log("1. GET /hello              → Response text");
  console.log("2. GET /html               → Response HTML");
  console.log("3. GET /api/user           → Response JSON");
  console.log("4. GET /api/status/:code   → Coba: 200, 400, 404, 500");
  console.log("5. GET /old-page           → Redirect ke /html");
  console.log("6. GET /download           → Download file");
  console.log("7. POST /api/login         → Login simulation");
  console.log("8. PUT /api/users/:id      → Update user");
  console.log("9. DELETE /api/users/:id   → Delete user");
  console.log("10. GET /simulate-error    → Simulasi error");
  console.log("");
  console.log("💡 TEST DENGAN:");
  console.log("- Browser untuk GET request");
  console.log("- Postman untuk POST/PUT/DELETE");
  console.log("=".repeat(40));
});

3.6 Cara Testing dengan Browser dan Postman

Testing di Browser:

  1. Jalankan server:node http-practice.js
  2. Buka Chrome, kunjungi:
  • http://localhost:3001/hello → Lihat text response
  • http://localhost:3001/html → Lihat HTML
  • http://localhost:3001/api/user → Lihat JSON
  • http://localhost:3001/api/status/404 → Lihat error 404

Testing dengan Postman:

  1. Buka Postman

  2. POST Request:

    • Method: POST

    • URL: http://localhost:3001/api/login

    • Headers: Content-Type: application/json

    • Body (raw JSON):

      json
      {
        "username": "admin",
        "password": "12345"
      }
    • Klik Send → Lihat response

  3. PUT Request:

    • Method: PUT

    • URL: http://localhost:3001/api/users/5

    • Body:

      json
      {
        "name": "Budi Updated",
        "email": "budi.new@email.com"
      }

3.7 Melihat Detail HTTP di Browser DevTools

Cara lihat request-response detail:

  1. Buka Chrome
  2. Tekan F12 atau Ctrl+Shift+I
  3. Pilih tab Network
  4. Buka http://localhost:3001/api/user
  5. Klik request yang muncul
  6. Lihat: 
    • Headers → Request dan response headers
    • Preview → Tampilan response
    • Response → Data mentah response
    • Status → Status code (200, 404, dll)

Contoh yang akan dilihat:

text
Request URL: http://localhost:3001/api/user
Request Method: GET
Status Code: 200 OK

Response Headers:
Content-Type: application/json; charset=utf-8
Date: Wed, 02 Feb 2024 08:30:00 GMT

Response Body:
{
  "success": true,
  "message": "Data user berhasil diambil",
  "data": { ... }
}

3.8 Contoh Request-Response dalam Kehidupan Nyata

Scenario: Login ke aplikasi

javascript
// CLIENT (Browser/Aplikasi) kirim REQUEST:
POST /api/login HTTP/1.1
Content-Type: application/json

{
  "email": "user@example.com",
  "password": "rahasia123"
}

// SERVER (Express kita) kasih RESPONSE:
HTTP/1.1 200 OK
Content-Type: application/json

{
  "success": true,
  "message": "Login berhasil",
  "token": "eyJhbGciOiJIUzI1NiIs...",
  "user": {
    "id": 1,
    "name": "John Doe",
    "email": "user@example.com"
  }
}

// Atau kalo gagal:
HTTP/1.1 401 Unauthorized
Content-Type: application/json

{
  "success": false,
  "error": "Login failed",
  "message": "Email atau password salah"
}

3.9 Common HTTP Headers yang Penting

javascript
// Headers untuk CORS (biar frontend bisa akses)
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');

// Headers untuk cache
res.setHeader('Cache-Control', 'no-cache'); // Jangan simpan cache

// Headers untuk security
res.setHeader('X-Content-Type-Options', 'nosniff');
res.setHeader('X-Frame-Options', 'DENY');

3.10 Latihan Praktikum

Exercise 1: Buat API Todo List

javascript
// TODO: Buat endpoint-endpoint berikut:
// 1. GET /api/todos     → Ambil semua todo
// 2. GET /api/todos/:id → Ambil todo by ID
// 3. POST /api/todos    → Buat todo baru
// 4. PUT /api/todos/:id → Update todo
// 5. DELETE /api/todos/:id → Hapus todo

// Data sementara (simpan di memory)
let todos = [
  { id: 1, task: "Belajar Express.js", completed: false },
  { id: 2, task: "Buat API todo", completed: true }
];

Exercise 2: Buat Response dengan Kondisi

javascript
// Buat endpoint /api/weather?city=jakarta
// Jika city ada: response 200 dengan data cuaca
// Jika city tidak ada: response 404
// Jika parameter city kosong: response 400

3.11 Troubleshooting HTTP

Problem: CORS Error di Browser

text
Access to fetch at 'http://localhost:3001/api/user' from origin 'http://localhost:5173' 
has been blocked by CORS policy

Solusi:

javascript
// Install CORS package
npm install cors

// Di server.js
const cors = require('cors');
app.use(cors()); // Tambah ini sebelum routes

Problem: Request Body Undefined

javascript
// Jika req.body undefined, tambah middleware:
app.use(express.json()); // Untuk JSON
app.use(express.urlencoded({ extended: true })); // Untuk form data

Problem: Status Code Selalu 200

javascript
// Pastikan panggil res.status() sebelum res.json()
res.status(201).json({ message: "Created" }); // ✅ Benar
res.json({ message: "Created" }).status(201); // ❌ Salah

4. Daftar Pustaka

  1. Telkom University (2024). Pengertian HTTP: Fungsi, Cara Kerja, dan Manfaathttps://bif.telkomuniversity.ac.id
  2. Developer Mozilla (2026). HTTP Response Status Codeshttps://developer.mozilla.org
  3. Express.js Documentation (n.d.). Routing. https://expressjs.com
  4. Postman Learning Center (2024). HTTP Requests Tutorial. https://learning.postman.com
  5. W3Schools (n.d.). HTTP Request Methodshttps://www.w3schools.com

Posting Komentar

0 Komentar