Project Structure
real-estate-website/
├── server.js
├── package.json
├── public/
│ ├── index.html
│ ├── style.css
│ └── script.js
└── data/
└── listings.json
Step 1: Setup Node.js Server
- Initialize Node.js Project:
mkdir real-estate-website cd real-estate-website npm init -y npm install express
- Create
server.js
:
// server.js const express = require('express'); const fs = require('fs'); const path = require('path'); const app = express(); const PORT = process.env.PORT || 3000; app.use(express.static('public')); app.use(express.json()); // Endpoint to get listings app.get('/api/listings', (req, res) => { fs.readFile(path.join(__dirname, 'data', 'listings.json'), 'utf8', (err, data) => { if (err) { res.status(500).send('Error reading listings'); } else { res.json(JSON.parse(data)); } }); }); app.listen(PORT, () => { console.log(`Server is running on http://localhost:${PORT}`); });
Step 2: Create Frontend
- Create
index.html
in public/
:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Real Estate Listings</title> <link rel="stylesheet" href="style.css"> </head> <body> <h1>Real Estate Listings</h1> <div id="listings"></div> <script src="script.js"></script> </body> </html>
- Create
style.css
in public/
:
body { font-family: Arial, sans-serif; margin: 20px; } h1 { text-align: center; } #listings { display: flex; flex-wrap: wrap; justify-content: center; } .listing { border: 1px solid #ccc; margin: 10px; padding: 10px; width: 300px; }
- Create
script.js
in public/
:
// script.js fetch('/api/listings') .then(response => response.json()) .then(data => { const listingsDiv = document.getElementById('listings'); data.forEach(listing => { const listingDiv = document.createElement('div'); listingDiv.className = 'listing'; listingDiv.innerHTML = ` <h2>${listing.title}</h2> <p>${listing.description}</p> <p>Price: $${listing.price}</p> `; listingsDiv.appendChild(listingDiv); }); }) .catch(error => console.error('Error fetching listings:', error));
Step 3: Create Listings Data
- Create
listings.json
in data/
:
[ { "title": "Beautiful Family Home", "description": "A spacious home with a beautiful garden.", "price": 350000 }, { "title": "Modern Apartment", "description": "A stylish apartment in the city center.", "price": 250000 }, { "title": "Cozy Cottage", "description": "A charming cottage in a quiet neighborhood.", "price": 180000 } ]
Step 4: Run the Application
- Start the Server:bashCopy code
node server.js
- Access the Application:Open your browser and go to
http://localhost:3000
.
Leave a Reply