// Import package yang diperlukanconstexpress=require('express');constcors=require('cors');constdotenv=require('dotenv');// Konfigurasi dotenvdotenv.config();// Inisialisasi expressconstapp=express();// Middlewareapp.use(cors());app.use(express.json());// Route test sederhanaapp.get('/api/test', (req, res) => {res.json({ message:'API Aplikasi Presensi berjalan dengan baik' });});// Jalankan serverconstPORT=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:
constexpress=require('express');constrouter=express.Router();// GET: Mengambil data usersrouter.get('/', (req, res) => {res.json({ users: [ { id:1, name:'User 1' }, { id:2, name:'User 2' } ] });});// POST: Membuat user barurouter.post('/', (req, res) => {const { name,email } =req.body;res.status(201).json({ message:'User berhasil dibuat', user: { name, email } });});// PUT: Update userrouter.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 userrouter.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 routesconstuserRoutes=require('./routes/userRoutes');// Gunakan routesapp.use('/api/users', userRoutes);// ... kode setelahnya ...