📅 Date: June 26, 2026
🧠 Mood: The Integrator 🔌
🔥 Topic: Web Dev Day 21: Vanilla JS API Integration
🌐 Bringing the Data to Life
An API is useless if users can't interact with it. Today, I moved into the cinemetrics-frontend directory to build the user interface. Before relying on heavy frameworks like React, it is crucial to understand how the browser natively communicates with servers.
I structured the dashboard using standard HTML5 and applied a dark-themed CSS stylesheet. The real magic, however, happened inside app.js, where I utilized the modern JavaScript Fetch API to bridge the gap between my UI and the Node.js server.
⚡ The Fetch API & DOM Manipulation
To display the top genre analytics we built yesterday, the frontend needs to make an asynchronous HTTP request to our backend, wait for the JSON response, and dynamically update the DOM.
// app.js - Frontend Integration
const API_URL = 'http://localhost:5000/api/movies';
const topGenreDisplay = document.getElementById('top-genre');
// Async function to fetch and display analytics
async function loadAnalytics() {
try {
// 1. Await the network request
const response = await fetch(`${API_URL}/analytics`);
// 2. Parse the JSON data
const result = await response.json();
// 3. Update the DOM securely
if (result.success && result.data.length > 0) {
const stats = result.data[0];
topGenreDisplay.innerText = `Top Genre: ${stats._id} (${stats.count} watched)`;
} else {
topGenreDisplay.innerText = "Add more movies to see analytics!";
}
} catch (error) {
console.error("Failed to connect to the CineMetrics Server", error);
topGenreDisplay.innerText = "Error loading data.";
}
}
// Trigger function on page load
document.addEventListener('DOMContentLoaded', loadAnalytics);
🛡️ Overcoming the CORS Error
The moment I tried to fetch data from my frontend (running on port 5500) to my backend (running on port 5000), the browser blocked it with a massive red CORS Policy error. Browsers block cross-origin requests for security reasons. I had to jump back into my server.js file and explicitly install and configure the cors middleware to allow my frontend to safely pull the data.
🎯 Phase 1 Complete
CineMetrics Phase 1 is officially live locally. The frontend seamlessly communicates with the database, proving the architecture works. As per the PRD, Phase 2 will introduce User Authentication (JWT) and social networking features. But for now, it's time to celebrate a successful deployment.
No comments:
Post a Comment