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:
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
Buat file /presensi-app/backend/.env
:
PORT=5000
MONGODB_URI=mongodb://localhost:27017/presensi-app
Buat file /presensi-app/backend/.gitignore
:
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
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;
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
Buat Collection baru di Postman:
Nama: "Aplikasi Presensi API"
Buat request untuk setiap endpoint
Test Route GET /api/users
:
URL: http://localhost:5000/api/users
Expected Response (200 OK):
{
"users": [
{ "id": 1, "name": "User 1" },
{ "id": 2, "name": "User 2" }
]
}
Test Route POST /api/users
:
URL: http://localhost:5000/api/users
Headers:
Content-Type: application/json
{
"name": "John Doe",
"email": "john@example.com"
}
Test Route PUT /api/users/:id
:
URL: http://localhost:5000/api/users/1
{
"name": "John Doe Updated"
}
Test Route DELETE /api/users/:id
:
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
Buat file /presensi-app/backend/config/db.js
untuk koneksi MongoDB
Buat file /presensi-app/backend/models/User.js
untuk model User
Buat file /presensi-app/backend/controllers/userController.js
untuk logic
Buat file /presensi-app/backend/middleware/auth.js
untuk authentication