HTML Basics
Assignment 1: Basic HTML
<h1>Hello, HTML!</h1>
CSS Fundamentals
Assignment 1: Styling a Page
<style> h1 { color: red; } </style> <h1>Styled Heading</h1>
JavaScript Introduction
Assignment 1: Console Logging
console.log("Hello, JavaScript!");
🚀 Introduction to Fetch API & Asynchronous JavaScript
1️⃣ JavaScript is Single-Threaded
- JavaScript executes line by line, meaning it can only do one thing at a time (single-threaded).
- If a task takes time (like fetching data from a server), it can block execution.
- To solve this problem, asynchronous operations allow handling such tasks without stopping other code from running.
2️⃣ What is Fetch API?
- The Fetch API is a modern way to make HTTP requests in JavaScript.
- It replaces older methods like XMLHttpRequest (which was complex to use).
- Fetch uses Promises to handle asynchronous requests.
📌 Fetch API Syntax:
fetch('https://jsonplaceholder.typicode.com/users') .then(response => response.json()) // Convert response to JSON .then(data => console.log(data)) // Handle the fetched data .catch(error => console.error("Error fetching data:", error)); // Handle errors // 🔹 fetch(url): Sends a request to the given URL. // 🔹 .then(response => response.json()): Converts the response to JSON format. // 🔹 .catch(error => console.error(error)): Catches any errors (e.g., network issues).
3️⃣ Understanding Promises
- A Promise represents a value that might be available now, in the future, or never.
- Promises have three states:
- Pending: The operation is still in progress.
- Resolved (Fulfilled): The operation was successful.
- Rejected: The operation failed.
📌 Basic Promise Syntax:
const myPromise = new Promise((resolve, reject) => { setTimeout(() => { let success = true; if (success) { resolve("✅ Operation Successful!"); } else { reject("❌ Operation Failed!"); } }, 2000); }); myPromise .then(result => console.log(result)) // Runs if resolved .catch(error => console.error(error)); // Runs if rejected // 🔹 resolve(): Marks the promise as fulfilled (success). // 🔹 reject(): Marks the promise as failed.
4️⃣ Fetch API with Promises
The Fetch API returns a Promise, which means you can handle it using .then() and .catch().
📌 Example of Fetch with Promises
fetch("https://jsonplaceholder.typicode.com/posts/1") .then(response => response.json()) // Convert to JSON .then(data => console.log("Fetched Data:", data)) // Handle success .catch(error => console.error("Error:", error)); // Handle error
5️⃣ Async & Await in Fetch API
- The async/await syntax provides a cleaner way to work with Promises.
- It allows writing asynchronous code that looks like synchronous code.
📌 Example: Fetching Data using Async/Await
async function fetchData() { try { let response = await fetch("https://jsonplaceholder.typicode.com/todos/1"); let data = await response.json(); console.log("Data:", data); } catch (error) { console.error("Error fetching data:", error); } } fetchData(); // 🔹 async function: Declares an asynchronous function. // 🔹 await fetch(url): Waits for the request to complete. // 🔹 try...catch: Handles errors gracefully.
6️⃣ Try-Catch with Promises
- We use try...catch to handle errors inside an async function.
📌 Example: Using Try-Catch
async function fetchUsers() { try { let response = await fetch("https://jsonplaceholder.typicode.com/users"); if (!response.ok) { // Checks if the response is successful throw new Error(`HTTP Error! Status: ${response.status}`); } let users = await response.json(); console.log("Users List:", users); } catch (error) { console.error("Failed to fetch users:", error); } } fetchUsers(); // 🔹 if (!response.ok): Ensures the response is successful before processing data. // 🔹 throw new Error(): Throws a custom error message if the request fails.
📌 Practice Assignment:
✅ Task
- 🔹 Fetch and display a list of users from an API.
- 🔹 Implement error handling.
- 🔹 Modify the response and display it on a webpage.
Assignment 2: Fetch API & Asynchronous JavaScript
1. Fetch and display a list of users from an API
Fetch and display a list of users from an API. Implement error handling and display results dynamically.
async function fetchUsers() { try { let response = await fetch("https://jsonplaceholder.typicode.com/users"); if (!response.ok) { throw new Error(`HTTP Error! Status: ${response.status}`); } let users = await response.json(); displayUsers(users); } catch (error) { console.error("Error:", error); } } function displayUsers(users) { let userList = document.getElementById("userList"); userList.innerHTML = ""; users.forEach(user => { let li = document.createElement("li"); li.textContent = `${user.name} - ${user.email}`; userList.appendChild(li); }); console.log("Users displayed successfully!"); }
2. Modify the response and display it on a webpage
Modify the fetched response and display it dynamically on a webpage with styled cards.
<style> .user-container { display: flex; flex-wrap: wrap; gap: 15px; margin-top: 20px; } .user-card { background: linear-gradient(145deg, #ffffff, #f0f0f0); border-radius: 10px; box-shadow: 0 4px 8px rgba(0,0,0,0.1); padding: 15px; width: 250px; transition: transform 0.3s, box-shadow 0.3s; } .user-card:hover { transform: translateY(-5px); box-shadow: 0 6px 12px rgba(0,0,0,0.15); } .user-name { color: #2575fc; font-size: 18px; margin: 0 0 5px 0; font-weight: bold; } .user-email { color: #666; font-size: 14px; margin: 5px 0; } .user-details { margin-top: 10px; font-size: 14px; color: #555; } .load-btn { background: linear-gradient(135deg, #6a11cb, #2575fc); color: white; border: none; padding: 10px 20px; border-radius: 5px; cursor: pointer; font-weight: bold; transition: transform 0.2s; } .load-btn:hover { transform: scale(1.05); } </style> <button class="load-btn" onclick="fetchUsers()">Load Users</button> <div class="user-container" id="userList"></div> <script> async function fetchUsers() { try { document.getElementById('userList').innerHTML = '<p>Loading...</p>'; let response = await fetch("https://jsonplaceholder.typicode.com/users"); if (!response.ok) { throw new Error(`HTTP Error! Status: ${response.status}`); } let users = await response.json(); displayUsers(users); } catch (error) { document.getElementById('userList').innerHTML = `<p>Error: ${error.message}</p>`; } } function displayUsers(users) { let userList = document.getElementById("userList"); userList.innerHTML = ""; users.forEach(user => { let card = document.createElement("div"); card.className = "user-card"; let name = document.createElement("h3"); name.className = "user-name"; name.textContent = user.name; let email = document.createElement("p"); email.className = "user-email"; email.textContent = user.email; let details = document.createElement("div"); details.className = "user-details"; details.innerHTML = ` <p>Username: ${user.username}</p> <p>Company: ${user.company.name}</p> <p>Website: ${user.website}</p> <p>Phone: ${user.phone}</p> `; card.appendChild(name); card.appendChild(email); card.appendChild(details); userList.appendChild(card); }); } </script>
Node.js Fundamentals
Assignment 1: Basic HTTP Server
Create a simple HTTP server that responds with "Hello from Node.js!"
const http = require('http'); const server = http.createServer((req, res) => { res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('Hello from Node.js!'); }); server.listen(3000, () => { console.log('Server running at http://localhost:3000/'); });
Assignment 2: Express.js Routing
Create an Express.js application with basic routing and middleware.
const express = require('express'); const app = express(); // Middleware example app.use((req, res, next) => { console.log(`${req.method} request to ${req.url}`); next(); }); // Routes app.get('/', (req, res) => { res.send('Welcome to Express.js!'); }); app.get('/api/users', (req, res) => { const users = [ { id: 1, name: 'John' }, { id: 2, name: 'Jane' } ]; res.json(users); }); app.listen(3000, () => { console.log('Express server running on port 3000'); });
Assignment 3: MongoDB Integration
Connect to MongoDB and perform basic CRUD operations.
const mongoose = require('mongoose'); // Connect to MongoDB mongoose.connect('mongodb://localhost/demo', { useNewUrlParser: true, useUnifiedTopology: true }); // Define User Schema const userSchema = new mongoose.Schema({ name: String, email: String, age: Number }); const User = mongoose.model('User', userSchema); // Create a new user async function createUser() { try { const user = await User.create({ name: 'John Doe', email: 'john@example.com', age: 30 }); console.log('User created:', user); // Find all users const users = await User.find(); console.log('All users:', users); } catch (error) { console.error('Error:', error); } } createUser();