Spaces:
Sleeping
Sleeping
| const express = require('express'); | |
| const path = require('path'); | |
| const fs = require('fs').promises; | |
| const app = express(); | |
| const port = 7860; | |
| // Set EJS as the templating engine | |
| app.set('view engine', 'ejs'); | |
| app.set('views', path.join(__dirname, 'views')); | |
| // Serve the dist directory as a static folder | |
| app.use('/api', express.static(path.join(__dirname, 'data'))); | |
| // Route to render the EJS testing page | |
| app.get('/', async (req, res) => { | |
| try { | |
| const provincesData = await fs.readFile(path.join(__dirname, 'data', 'provinces.json'), 'utf8'); | |
| const provinces = JSON.parse(provincesData); | |
| res.render('index', { provinces }); | |
| } catch (error) { | |
| console.error(error); | |
| res.status(500).send('Error loading province data.'); | |
| } | |
| }); | |
| // API endpoint for provinces | |
| app.get('/api/provinces', async (req, res) => { | |
| try { | |
| const data = await fs.readFile(path.join(__dirname, 'data', 'provinces.json'), 'utf8'); | |
| res.json(JSON.parse(data)); | |
| } catch (error) { | |
| res.status(404).json({ error: 'Provinces not found' }); | |
| } | |
| }); | |
| // API endpoint for regencies in a specific province | |
| app.get('/api/provinces/:provinceId/regencies', async (req, res) => { | |
| const { provinceId } = req.params; | |
| try { | |
| const data = await fs.readFile(path.join(__dirname, 'data', provinceId, 'regencies.json'), 'utf8'); | |
| res.json(JSON.parse(data)); | |
| } catch (error) { | |
| res.status(404).json({ error: 'Regencies not found for this province' }); | |
| } | |
| }); | |
| // API endpoint for districts in a specific regency | |
| app.get('/api/provinces/:provinceId/regencies/:regencyId/districts', async (req, res) => { | |
| const { provinceId, regencyId } = req.params; | |
| try { | |
| const data = await fs.readFile(path.join(__dirname, 'data', provinceId, regencyId, 'district.json'), 'utf8'); | |
| res.json(JSON.parse(data)); | |
| } catch (error) { | |
| res.status(404).json({ error: 'Districts not found for this regency' }); | |
| } | |
| }); | |
| // API endpoint for villages (subdistricts) in a specific district | |
| app.get('/api/provinces/:provinceId/regencies/:regencyId/districts/:districtId/villages', async (req, res) => { | |
| const { provinceId, regencyId, districtId } = req.params; | |
| try { | |
| const data = await fs.readFile(path.join(__dirname, 'data', provinceId, regencyId, districtId, 'subdistrict.json'), 'utf8'); | |
| res.json(JSON.parse(data)); | |
| } catch (error) { | |
| res.status(404).json({ error: 'Villages not found for this district' }); | |
| } | |
| }); | |
| app.listen(port, () => { | |
| console.log(`Server is running on http://localhost:${port}`); | |
| }); |