Bab 2: Backend Development - Dasar - Membuat Server Express

Bab 2.1: Membuat Server Express

1. Membuat Project Node.js

Pertama, buat struktur folder dasar:

# Buat folder utama
mkdir presensi-app
cd presensi-app

# Buat folder frontend dan backend
mkdir frontend backend
cd backend

Di dalam folder /presensi-app/backend, inisialisasi project Node.js:

npm init -y

Isi detail project di presensi-app/backend/package.json:

{
  "name": "presensi-app-backend",
  "version": "1.0.0",
  "description": "Backend untuk aplikasi presensi menggunakan Express",
  "main": "server.js",
  "scripts": {
    "start": "node server.js",
    "dev": "nodemon server.js"
  },
  "author": "Nama Anda",
  "license": "ISC"
}

2. Instalasi Package yang Diperlukan

Di folder /presensi-app/backend, install package yang dibutuhkan:

# Install package utama
npm install express mongoose dotenv cors

# Install package development
npm install --save-dev nodemon

3. Membuat Struktur Folder

Buat folder-folder berikut di dalam /presensi-app/backend:

mkdir config controllers models routes middleware

Struktur folder lengkap:

presensi-app/
├── backend/
│   ├── config/
│   │   └── db.js
│   ├── controllers/
│   │   └── userController.js
│   ├── models/
│   │   └── User.js
│   ├── routes/
│   │   └── userRoutes.js
│   ├── middleware/
│   │   └── auth.js
│   ├── .env
│   ├── .gitignore
│   ├── package.json
│   └── server.js
└── frontend/

4. Setup File Konfigurasi

  1. Buat file /presensi-app/backend/.env:

PORT=5000
MONGODB_URI=mongodb://localhost:27017/presensi-app
  1. Buat file /presensi-app/backend/.gitignore:

node_modules
.env

5. Setup Server Express

Buat file /presensi-app/backend/server.js:

// Import package yang diperlukan
const express = require('express');
const cors = require('cors');
const dotenv = require('dotenv');

// Konfigurasi dotenv
dotenv.config();

// Inisialisasi express
const app = express();

// Middleware
app.use(cors());
app.use(express.json());

// Route test sederhana
app.get('/api/test', (req, res) => {
  res.json({
    message: 'API Aplikasi Presensi berjalan dengan baik'
  });
});

// Jalankan server
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => {
  console.log(`Server berjalan di port ${PORT}`);
});

6. Implementasi Routes Dasar

  1. Buat file /presensi-app/backend/routes/userRoutes.js:

const express = require('express');
const router = express.Router();

// GET: Mengambil data users
router.get('/', (req, res) => {
  res.json({
    users: [
      { id: 1, name: 'User 1' },
      { id: 2, name: 'User 2' }
    ]
  });
});

// POST: Membuat user baru
router.post('/', (req, res) => {
  const { name, email } = req.body;
  res.status(201).json({
    message: 'User berhasil dibuat',
    user: { name, email }
  });
});

// PUT: Update user
router.put('/:id', (req, res) => {
  const { id } = req.params;
  const { name } = req.body;
  res.json({
    message: `User dengan id ${id} berhasil diupdate`,
    user: { id, name }
  });
});

// DELETE: Hapus user
router.delete('/:id', (req, res) => {
  const { id } = req.params;
  res.json({
    message: `User dengan id ${id} berhasil dihapus`
  });
});

module.exports = router;
  1. Update file /presensi-app/backend/server.js untuk menambahkan routes:

// ... kode sebelumnya ...

// Import routes
const userRoutes = require('./routes/userRoutes');

// Gunakan routes
app.use('/api/users', userRoutes);

// ... kode setelahnya ...

7. Testing API dengan Postman

  1. Buat Collection baru di Postman:

    • Nama: "Aplikasi Presensi API"

    • Buat request untuk setiap endpoint

  2. Test Route GET /api/users:

    • Method: GET

    • URL: http://localhost:5000/api/users

    • Expected Response (200 OK):

    {
      "users": [
        { "id": 1, "name": "User 1" },
        { "id": 2, "name": "User 2" }
      ]
    }
  3. Test Route POST /api/users:

    • Method: POST

    • URL: http://localhost:5000/api/users

    • Headers:

      Content-Type: application/json
    • Body (raw JSON):

    {
      "name": "John Doe",
      "email": "john@example.com"
    }
  4. Test Route PUT /api/users/:id:

    • Method: PUT

    • URL: http://localhost:5000/api/users/1

    • Body (raw JSON):

    {
      "name": "John Doe Updated"
    }
  5. Test Route DELETE /api/users/:id:

    • Method: DELETE

    • URL: http://localhost:5000/api/users/1

8. Menjalankan Server

Di folder /presensi-app/backend:

# Development mode dengan nodemon
npm run dev

# Production mode
npm start

Langkah Selanjutnya

  1. Buat file /presensi-app/backend/config/db.js untuk koneksi MongoDB

  2. Buat file /presensi-app/backend/models/User.js untuk model User

  3. Buat file /presensi-app/backend/controllers/userController.js untuk logic

  4. Buat file /presensi-app/backend/middleware/auth.js untuk authentication

Last updated