diff --git a/absolute-beginners/full-stack/backend/error-handling.mdx b/absolute-beginners/full-stack/backend/error-handling.mdx index e345ed2..8f3e910 100644 --- a/absolute-beginners/full-stack/backend/error-handling.mdx +++ b/absolute-beginners/full-stack/backend/error-handling.mdx @@ -1 +1,121 @@ - \ No newline at end of file +--- +title: "Error Handling in Express" +sidebar_label: "5. Error Handling" +sidebar_position: 5 +description: "Learn how to catch and handle errors in your Node.js and Express applications to prevent crashes." +tags: ["Error Handling", "Express.js", "Node.js", "Backend Development"] +keywords: ["Error Handling", "Express.js", "Node.js", "Try...Catch", "Error Middleware", "Custom Errors", "404 Handling"] +--- + +In a basic script, if an error happens, the program stops. In a backend server, if the program stops, your entire website goes offline for everyone! Error handling is the art of catching those "oops" moments and responding gracefully. + +## 1. The Try...Catch Block + +The most basic way to handle errors in JavaScript is the `try...catch` block. You "try" to run some code, and if it fails, the "catch" block takes over. + +```javascript title="server.js" +app.get('/api/data', async (req, res) => { + try { + const data = await someDatabaseCall(); + res.json(data); + } catch (error) { + console.error(error); // Log it for the developer + res.status(500).send("Something went wrong on our end!"); + } +}); +``` + +## 2. Express Error Middleware + +Express has a special type of middleware specifically for errors. While normal middleware has three arguments `(req, res, next)`, error middleware has **four**: `(err, req, res, next)`. + +If you place this at the very bottom of your `server.js` (after all your routes), it will catch every error that happens in your app. + +```javascript title="server.js" +// Universal Error Handler +app.use((err, req, res, next) => { + console.error(err.stack); + res.status(500).json({ + success: false, + message: "Internal Server Error", + error: err.message // Optional: only show in development + }); +}); +``` + +## 3. Throwing Custom Errors + +Sometimes, the code isn't "broken," but the user did something wrong (like entering the wrong password). In these cases, you can "throw" your own error to trigger the catch block. + +```javascript title="server.js" +app.post('/login', (req, res, next) => { + const { password } = req.body; + + if (password !== "12345") { + const error = new Error("Wrong Password!"); + error.status = 401; + return next(error); // Passes the error to the error middleware + } + + res.send("Logged in!"); +}); +``` + +## 4. Handling 404 (Not Found) + +What happens if a user visits a URL that doesn't exist? By default, Express sends a plain text message. At the Hub, we prefer to send a clean JSON response or a custom 404 page. + +**Add this right before your error middleware:** + +```javascript title="server.js" +app.use((req, res) => { + res.status(404).json({ message: "Requested resource not found" }); +}); +``` + +## 5. Best Practices for Error Messages + +When an error occurs, you must be careful about what you tell the user: + +| Scenario | Good Response | Bad Response | +| :--- | :--- | :--- | +| **Database Failed** | "Service temporarily unavailable." | "Error: Cannot connect to MongoDB at 192.168..." | +| **Wrong Input** | "Please enter a valid email." | "Internal logic failed at line 42." | +| **Security** | "Invalid credentials." | "That email exists, but the password is wrong." | + +:::tip +Never reveal your database structure or file paths in an error message. It gives hackers a map of your server! +::: + +## Practice: The "Safe Divider" + +Build a route `/divide/:a/:b` that: +1. Takes two numbers from the URL. +2. Divides `a` by `b`. +3. **Error Check:** If `b` is `0`, throw an error (you can't divide by zero!). +4. **Error Check:** If `a` or `b` are not numbers, throw an error. + +```javascript title="server.js" +app.get('/divide/:a/:b', (req, res, next) => { + const a = parseFloat(req.params.a); + const b = parseFloat(req.params.b); + + if (isNaN(a) || isNaN(b)) { + const error = new Error("Both parameters must be numbers."); + error.status = 400; + return next(error); + } + + if (b === 0) { + const error = new Error("Cannot divide by zero."); + error.status = 400; + return next(error); + } + + res.json({ result: a / b }); +}); +``` + +:::info Async Wrapper +In modern Express, catching errors in `async` functions can be repetitive. Many developers use a "Catch-Async" helper function or a library like `express-async-errors` to automatically catch errors and send them to the global error handler. +::: \ No newline at end of file diff --git a/absolute-beginners/full-stack/backend/express.mdx b/absolute-beginners/full-stack/backend/express.mdx index e345ed2..805a1d2 100644 --- a/absolute-beginners/full-stack/backend/express.mdx +++ b/absolute-beginners/full-stack/backend/express.mdx @@ -1 +1,118 @@ - \ No newline at end of file +--- +title: "Express.js Framework" +sidebar_label: "3. Express.js" +sidebar_position: 3 +description: "Learn how to build a web server quickly using Express.js, the most popular Node.js framework. Understand routing, middleware, and how to handle requests and responses. Get hands-on experience creating your first API endpoints." +tags: ["Express.js", "Backend", "Node.js", "Web Server", "API"] +keywords: ["Express.js", "Web Framework", "Routing", "Middleware", "API Endpoints", "Node.js"] +--- + +If Node.js is the "Environment," then **Express.js** is the "Framework." It is designed to make building web applications and APIs much easier and faster. At **CodeHarborHub**, we use Express because it is the industry standard for JavaScript backends. + +## 1. Why use Express? + +Building a server using only built-in Node.js `http` module is like building a house by making your own bricks. Express gives you the bricks already made: +* **Easy Routing:** Define what happens when a user visits `/home` vs `/profile`. +* **Middleware Support:** Add extra features like logging or security with one line of code. +* **JSON Friendly:** Perfect for talking to React frontends. + +## 2. Setting Up Express + +First, create a folder for your project, initialize it, and install Express: + +```bash +mkdir my-server +cd my-server +npm init -y +npm install express +``` + +## 3. The "Hello World" Server + +Create a file named `server.js` and add this code. This is the simplest Express server possible: + +```javascript title="server.js" +const express = require('express'); +const app = express(); +const PORT = 3000; + +// This is a "Route" +app.get('/', (req, res) => { + res.send('Welcome to the CodeHarborHub Server!'); +}); + +app.listen(PORT, () => { + console.log(`Server is running at http://localhost:${PORT}`); +}); +``` + +To start it, run `node server.js` in your terminal. Open your browser and go to `http://localhost:3000`. + +## 4. Understanding Request and Response + +Every route handler in Express gives you two important objects: + +1. **`req` (Request):** Information coming *from* the user (e.g., what they typed in a search bar). +2. **`res` (Response):** What the server sends *back* to the user (e.g., text, HTML, or an image). + +## 5. Handling Routes (The Roadmap) + +A "Route" is a combination of a **URL** and an **HTTP Method**. The most common methods are: +* **GET:** To "Get" data (e.g., reading a blog post). +* **POST:** To "Send" data (e.g., creating a new user account). +* **PUT:** To "Update" data (e.g., changing your profile picture). +* **DELETE:** To "Remove" data. + +```javascript title="server.js" +const express = require('express'); +const app = express(); +app.use(express.json()); + +app.get('/api/cricket', (req, res) => { + res.json({ player: "MS Dhoni", shot: "Helicopter Shot" }); +}); + +app.post('/api/login', (req, res) => { + res.send("Processing login..."); +}); +``` + +## 6. Nodemon: The Developer's Best Friend + +Normally, every time you change your code, you have to stop and restart the server manually. **Nodemon** does this for you automatically! + +**Install it:** + +```bash +npm install -g nodemon +``` + +**Run your server with it:** + +```bash +nodemon server.js +``` + +## Practice: The Dynamic Greeter + +Let's use **URL Parameters** to greet users by name! + +```javascript title="server.js" +const express = require('express'); +const app = express(); + +app.get('/greet/:name', (req, res) => { + const userName = req.params.name; + res.send(`Hello ${userName}, welcome to the backend!`); +}); +``` + +*If you visit `http://localhost:3000/greet/Ajay`, the page will say "Hello Ajay, welcome to the backend!"* + +:::info Middleware +Middleware functions are functions that have access to the request and response objects. They run *before* your route handler. A very common one is `express.json()`, which allows your server to read JSON data sent from the frontend. + +```javascript title="server.js" +app.use(express.json()); +``` +::: \ No newline at end of file diff --git a/absolute-beginners/full-stack/backend/middleware.mdx b/absolute-beginners/full-stack/backend/middleware.mdx index e345ed2..ade8e01 100644 --- a/absolute-beginners/full-stack/backend/middleware.mdx +++ b/absolute-beginners/full-stack/backend/middleware.mdx @@ -1 +1,117 @@ - \ No newline at end of file +--- +title: "Understanding Middleware in Express" +sidebar_label: "6. Middleware" +sidebar_position: 6 +description: "Learn how to use and create middleware to process requests before they reach your routes." +tags: ["Middleware", "Express.js", "Node.js", "Backend Development"] +keywords: ["Middleware", "Express.js", "Node.js", "Custom Middleware", "Built-in Middleware", "Third-Party Middleware", "next() Function"] +--- + +In Express, **Middleware** is a function that runs **after** the incoming request is received and **before** the final response is sent. It has access to the Request (`req`), Response (`res`), and the next function in the cycle. + +## 1. How Middleware Works + +Think of Middleware as a series of checkpoints. Each middleware can: +1. Execute any code. +2. Make changes to the `req` and `res` objects. +3. End the request-response cycle (e.g., if a user isn't logged in). +4. Call the **`next()`** function to pass control to the next middleware. + +```javascript title="server.js" +app.use((req, res, next) => { + console.log("This runs for every request!"); + next(); // Passes control to the next middleware or route handler +}); +``` + +## 2. Types of Middleware + +### 1. Built-in Middleware +Express comes with some tools already included. The most common one is `express.json()`, which helps your server understand JSON data sent by a frontend (like a React app). + +```javascript title="server.js" +app.use(express.json()); // Essential for modern apps! +``` + +### 2. Third-Party Middleware +The community has built amazing tools that you can install via NPM. +* **Morgan:** Logs every request so you can see who is visiting your site. +* **Cors:** Allows your frontend to talk to your backend safely. +* **Dotenv:** Helps manage "secret" environment variables. + +```bash +npm install morgan +``` + +Now, let's use it in our `server.js`: + +```javascript title="server.js" +const morgan = require('morgan'); +app.use(morgan('dev')); // Now every request shows up in your terminal! +``` + +### 3. Custom Middleware +You can write your own middleware to do anything you want! This is great for things like checking if a user is an admin or logging the time of a request. + +## 3. Building Your First Custom Middleware + +Let's create a "Logger" that prints the URL and the current time whenever someone visits our site. + +```javascript title="server.js" +const myLogger = (req, res, next) => { + const currentTime = new Date().toLocaleTimeString(); + console.log(`[${currentTime}] Request made to: ${req.url}`); + + // CRITICAL: You must call next() or the browser will hang forever! + next(); +}; + +// Apply it to the whole app +app.use(myLogger); +``` + +## 4. Global vs. Specific Middleware + +At **CodeHarborHub**, we teach you to be precise with your code. You don't always want middleware to run on *every* page. + +### Global Middleware + +Runs for every single route in your app. + +```javascript title="server.js" +app.use(express.json()); +``` + +### Specific Middleware + +Only runs for a specific route. This is perfect for "Protected Routes" (e.g., only users who are logged in can see `/dashboard`). + +```javascript title="server.js" +const checkAuth = (req, res, next) => { + const isAuthorized = true; // In real life, check for a token + if (isAuthorized) { + next(); + } else { + res.status(401).send("Access Denied!"); + } +}; + +app.get('/dashboard', checkAuth, (req, res) => { + res.send("Welcome to your secret dashboard!"); +}); +``` + +## 5. The Importance of `next()` + +If you forget to call `next()`, your request will get "stuck" in that middleware. The user's browser will show a spinning loading icon until it eventually times out. Always remember: **Middleware is a relay race—you must pass the baton!** + +## Practice: The "Maintenance Mode" Challenge + +Try to create a middleware that prevents anyone from visiting your site. +1. Create a middleware function. +2. Instead of calling `next()`, it should send a message: `"Site under maintenance. Check back later!"`. +3. Apply it to your app and try to visit any route. + +:::info Order Matters! +Express runs middleware in the order you write them in your code. If you put your error-handling middleware at the top, it won't catch any errors from the routes below it. Always place global middleware and routes first, and error handlers last. +::: \ No newline at end of file diff --git a/absolute-beginners/full-stack/backend/mini-projects.mdx b/absolute-beginners/full-stack/backend/mini-projects.mdx index e345ed2..d976fa9 100644 --- a/absolute-beginners/full-stack/backend/mini-projects.mdx +++ b/absolute-beginners/full-stack/backend/mini-projects.mdx @@ -1 +1,80 @@ - \ No newline at end of file +--- +title: "Backend Mini-Projects for Absolute Beginners" +sidebar_label: "Mini-Projects" +sidebar_position: 8 +description: "Build real-world server-side applications to master Node.js, Express, and MongoDB." +tags: ["Backend Projects", "Node.js", "Express.js", "MongoDB", "API Design", "Full-Stack Development"] +keywords: ["Backend Projects", "Node.js", "Express.js", "MongoDB", "API Design", "Full-Stack Development", "URL Shortener", "Expense Tracker", "Notes API", "Weather API"] +--- + +You've learned how to build servers, handle routes, and manage databases. Now, it's time to build independent services. These projects focus on **API Design**, **Data Persistence**, and **Logic**. + +## Project 1: The "CodeHarbor" URL Shortener + +**Focus:** *Express, MongoDB, NanoID* + +Build a service that takes a long URL and turns it into a short, shareable link. + +* **Requirements:** + * A `POST` route to accept a long URL and save it to MongoDB. + * Generate a unique short ID for each link. + * A `GET` route `/:shortId` that redirects the user to the original long URL. +* **Backend Challenge:** Track "Analytics"—every time a link is clicked, increment a `clicks` counter in your database. + +## Project 2: Personal Expense Tracker API + +**Focus:** *CRUD Operations, MVC Pattern* + +Create a system to manage daily expenses. This is a perfect exercise for practicing the **Model-View-Controller** structure. + +* **Requirements:** + * **Model:** `title`, `amount`, `category`, and `date`. + * **GET /expenses:** Fetch all records. + * **POST /expenses:** Add a new expense. + * **DELETE /expenses/:id:** Remove a record. +* **Logic Challenge:** Create a route `GET /expenses/total` that calculates the sum of all expenses using a MongoDB aggregation or a JavaScript `.reduce()` function. + +## Project 3: Secure "Master" Notes API + +**Focus:** *JWT Authentication, Middleware* + +Build a private note-taking backend where users can only see their own notes. + +* **Requirements:** + * **User Auth:** Signup and Login routes using **Bcrypt** for password hashing and **JWT** for tokens. + * **Protected Routes:** Use a custom `authMiddleware` to ensure only logged-in users can access the notes. + * **Association:** Each note in the database must be linked to a specific `userId`. +* **Security Challenge:** Ensure that User A cannot delete a note belonging to User B by checking ownership in the controller. + +## Project 4: AgriSense Weather & Log API + +**Focus:** *External APIs, Environment Variables* + +Integrate your backend with the real world. This project mimics the "AgriSense" minor project logic. + +* **Requirements:** + * Create a route that takes a city name and fetches weather data from the OpenWeather API. + * Save a "log" of every weather check in your database (City, Temp, Timestamp). + * **Environment Variables:** Use a `.env` file to keep your API keys secret. +* **Integration Challenge:** Build a "History" route that shows the last 5 weather searches made by any user. + +## The "Professional" Checklist + +Before you consider a project "Done" at the Hub, make sure it passes these checks: + +1. **Environment Setup:** Does it have a `.env.example` file? +2. **Status Codes:** Does it return `201` for creations and `404` for missing items? +3. **Validation:** Does the server crash if you send an empty body? (Use `Joi` or manual checks). +4. **Documentation:** Does your `README.md` explain how to install and what the API endpoints are? +5. **Error Handling:** Do you have a global error handler to catch unexpected bugs? + +## Submission & Portfolio + +A backend project doesn't have a "screenshot," but you can still show it off! +* **Postman/Thunder Client:** Export your collection so others can test your API. +* **Render/Railway:** Deploy your backend for free so your frontend projects can talk to a live URL. +* **GitHub:** Write a great README. Use clear commit messages like `feat: add user authentication`. + +:::tip Stuck? +Backend bugs are often "invisible." Use `console.log(req.body)` or the **VS Code Debugger** to see exactly what is happening inside your functions. If you get a `500` error, check your terminal—the answer is usually hiding in the stack trace! +::: \ No newline at end of file diff --git a/absolute-beginners/full-stack/backend/mvc-pattern.mdx b/absolute-beginners/full-stack/backend/mvc-pattern.mdx index e345ed2..e5c8611 100644 --- a/absolute-beginners/full-stack/backend/mvc-pattern.mdx +++ b/absolute-beginners/full-stack/backend/mvc-pattern.mdx @@ -1 +1,114 @@ - \ No newline at end of file +--- +title: "Understanding the MVC Pattern in Backend Development" +sidebar_label: "7. MVC Pattern" +sidebar_position: 7 +description: "Learn how to organize your backend code using the Model-View-Controller architecture for better maintainability." +tags: ["MVC Pattern", "Model-View-Controller", "Backend Architecture", "Code Organization", "Express.js"] +keywords: ["MVC Pattern", "Model-View-Controller", "Backend Architecture", "Code Organization", "Express.js", "Models", "Views", "Controllers"] +--- + +As a "Master" developer at the Hub, your goal isn't just to write code that *works*, but code that is *clean*. **MVC (Model-View-Controller)** is a design pattern that splits your application into three logical parts. + +:::tip Tip for Beginners +Think of MVC as organizing your closet. You have a section for shirts (Models), a section for pants (Controllers), and a section for shoes (Views). When you need to find something, you know exactly where to look! +::: + +## 1. What does MVC stand for? + +### M is for Model (The Data) + +The Model is the "Brain" of your data. It defines what your data looks like and how it interacts with the database. If you are building a Cricket app, the Model defines that a `Player` has a `name`, a `runs` count, and a `specialShot`. + +* **Responsibility:** Talking to the Database (MongoDB/SQL). +* **Analogy:** The Librarian who knows where every book is. + +### C is for Controller (The Logic) + +The Controller is the "Middleman." It receives the request from the user, processes it (maybe asks the Model for some data), and then sends a response back. + +* **Responsibility:** Handling "Routes" and deciding what to do. +* **Analogy:** The Waiter who takes your order to the kitchen and brings your food back. + +### V is for View (The Interface) + +The View is what the user sees. In a Full-Stack MERN app, your **React** frontend acts as the View. In a traditional backend, the View might be an HTML template. + +* **Responsibility:** Displaying the data in a pretty way. +* **Analogy:** The Plate and garnish that makes the food look delicious. + +## 2. Why bother with MVC? + +Imagine you want to change your database from MongoDB to PostgreSQL. +* **Without MVC:** You have to search through 50 files to find every line of database code. +* **With MVC:** You only change the **Model** files. The Controllers and Views don't care where the data comes from! + +## 3. A "Noob-Friendly" File Structure + +At **CodeHarborHub**, we recommend organizing your project folder like this: + +```text +/my-backend-app +├── /controllers +│ └── userController.js <-- (The Logic) +├── /models +│ └── userModel.js <-- (The Schema/Data) +├── /routes +│ └── userRoutes.js <-- (The URL Paths) +├── /views <-- (Templates, if not using React) +└── server.js <-- (The Entry Point) +``` + +In this structure: +* The **Controllers** folder contains all the logic for handling requests. +* The **Models** folder defines the structure of your data and how to interact with the database. +* The **Routes** folder maps URLs to Controller functions. +* The **Views** folder is where you would put HTML templates if you're not using a frontend framework like React. + +## 4. MVC in Action (Code Example) + +Let's see how a "Get User" request flows through MVC: + +**1. The Route (`/routes/userRoutes.js`):** The gatekeeper that points the URL to the Controller. + +```javascript title="userRoutes.js" +const express = require('express'); +const router = express.Router(); +const userController = require('../controllers/userController'); +router.get('/profile/:id', userController.getProfile); +``` + +**2. The Controller (`/controllers/userController.js`):** The brain that asks the Model for data. + +```javascript title="userController.js" +const User = require('../models/userModel'); + +exports.getProfile = async (req, res) => { + const userData = await User.findById(req.params.id); // Ask the Model + res.json(userData); // Send to the View (Frontend) +}; +``` + +**3. The Model (`/models/userModel.js`):** The definition of the data. + +```javascript title="userModel.js" +const mongoose = require('mongoose'); + +const userSchema = new mongoose.Schema({ + name: String, + email: String, + role: String +}); + +module.exports = mongoose.model('User', userSchema); +``` + +## Practice: The "AgriSense" Organization + +If you were building your **AgriSense** project (animal farming guide) using MVC: +1. What would the **Model** look like? (e.g., Animal name, species, diet). +2. What would the **Controller** do? (e.g., `getAnimalCareTips`). +3. How would the **View** (React) display it? (e.g., A clean card with images). + +:::tip Tip for Beginners +When you start, it’s okay to feel like this is "extra work." But once your app has more than 5 routes, MVC will save you hours of debugging. **Think of it as organizing your toolbox before starting a big project.** +::: \ No newline at end of file diff --git a/absolute-beginners/full-stack/backend/node-basics.mdx b/absolute-beginners/full-stack/backend/node-basics.mdx deleted file mode 100644 index e345ed2..0000000 --- a/absolute-beginners/full-stack/backend/node-basics.mdx +++ /dev/null @@ -1 +0,0 @@ - \ No newline at end of file diff --git a/absolute-beginners/full-stack/backend/nodejs-basics.mdx b/absolute-beginners/full-stack/backend/nodejs-basics.mdx new file mode 100644 index 0000000..8b8eaf1 --- /dev/null +++ b/absolute-beginners/full-stack/backend/nodejs-basics.mdx @@ -0,0 +1,108 @@ +--- +title: "Node.js Basics" +sidebar_label: "2. Node.js Basics" +sidebar_position: 2 +description: "Learn how to run JavaScript on your computer and understand the Node.js runtime environment. Get familiar with core modules, the global object, and how to share code using modules." +tags: ["Node.js", "Backend", "JavaScript"] +keywords: ["Node.js", "Runtime Environment", "Global Object", "Core Modules", "Modules", "CommonJS"] +--- + +What exactly is **Node.js**? It is not a programming language, and it is not a framework. It is a **Runtime Environment**. It takes the same engine that powers Google Chrome (the V8 engine) and lets it run directly on your computer's operating system. + +## 1. Why Node.js? + +At the Hub, we love Node.js for three main reasons: +1. **JavaScript Everywhere:** You don't need to learn a new language like Python or PHP for the backend. +2. **Blazing Fast:** Node.js is designed for "non-blocking" operations, making it perfect for real-time apps like chat or live cricket score updates. +3. **NPM (Node Package Manager):** Access to millions of ready-to-use code libraries created by the global community. + +## 2. Checking your Environment + +Before we start, make sure you have Node.js installed. Open your terminal and type: + +```bash +node -v +``` + +If you see a version number (like `v20.x.x`), you are ready to go! + +## 3. Running your first Node Script + +In the frontend, you had to link a `.js` file to an `.html` file to see it work. In Node, you run it directly. + +1. Create a file named `hello.js`. +2. Write the following code: + + ```javascript title="hello.js" + console.log("Welcome to the Backend, A Master!"); + + const colors = ["Red", "Green", "Blue"]; + console.log("Your available colors are:", colors); + ``` + +3. In your terminal, run: + + ```bash + node hello.js + ``` + +## 4. The `Global` Object + +In the browser, the top-level object is `window`. In Node.js, there is no window (because there is no browser!). Instead, the top-level object is called `global`. + +| Feature | Browser (Frontend) | Node.js (Backend) | +| :--- | :--- | :--- | +| **Global Object** | `window` | `global` | +| **DOM** | Access to `document` | **No DOM** | +| **File System** | Blocked for security | Can read/write files | +| **Location** | `location.href` | `process.cwd()` | + +## 5. Modules: Sharing Code + +Node.js uses a system called **CommonJS** to share code between files. You use `require` to import code and `module.exports` to send it out. + +```javascript title="math.js" +const add = (a, b) => a + b; +module.exports = add; +``` + +And then in another file, you can use it: + +```javascript title="app.js" +const add = require('./math'); +console.log("2 + 3 =", add(2, 3)); // Output: 2 + 3 = 5 +``` + +## 6. Core Modules + +Node.js comes with built-in "Superpowers" called Core Modules. You don't need to install them; you just import them. + +* **`fs` (File System):** To read and write files on your computer. +* **`path`:** To handle file and folder paths. +* **`http`:** To create a basic web server. + +### Example: Reading a File + +```javascript title="readFile.js" +const fs = require('fs'); + +fs.readFile('note.txt', 'utf8', (err, data) => { + if (err) throw err; + console.log("File content:", data); +}); +``` + +## Practice: The Greeting Machine + +1. Create a file named `greet.js`. +2. Use `process.argv` to get a name from the terminal command. +3. Run it like this: `node greet.js Ajay`. + +```javascript title="greet.js" +const name = process.argv[2] || "Guest"; +console.log(`Hello, ${name}! Welcome to CodeHarborHub.`); +``` + +:::info Package.json +Always start a new project by running `npm init -y`. This creates a `package.json` file, which is like a **manifest** for your project. It keeps track of your project's name, version, and the libraries you install. +::: \ No newline at end of file diff --git a/absolute-beginners/full-stack/backend/routing.mdx b/absolute-beginners/full-stack/backend/routing.mdx index e345ed2..ff36bc4 100644 --- a/absolute-beginners/full-stack/backend/routing.mdx +++ b/absolute-beginners/full-stack/backend/routing.mdx @@ -1 +1,132 @@ - \ No newline at end of file +--- +title: "Express Routing & Controllers" +sidebar_label: "4. Routing" +sidebar_position: 4 +description: "Learn how to organize your server paths and handle different HTTP methods. Understand how to use Express Router for modular code and Controllers for separating logic. Build a mini-library API to practice your routing skills." +tags: ["Express.js", "Routing", "Controllers", "Backend", "Node.js"] +keywords: ["Express.js", "Routing", "Controllers", "API Endpoints", "Node.js", "Backend Development"] +--- + +In the previous lesson, we created a basic server. But as your project grows, you can't put 100 different routes in a single `server.js` file. Routing allows us to split our application into small, manageable pieces. + +## 1. The Anatomy of a Route + +A route in Express follows this structure: +`app.METHOD(PATH, HANDLER)` + +* **`app`**: The instance of express. +* **`METHOD`**: The HTTP verb (GET, POST, PUT, DELETE). +* **`PATH`**: The URL on the server (e.g., `/api/users`). +* **`HANDLER`**: The function that runs when the route is matched. + +## 2. Route Parameters + +Sometimes parts of your URL are dynamic. For example, in [https://codeharborhub.github.io/our-team/details/?member=ajay-dhangar](https://codeharborhub.github.io/our-team/details/?member=ajay-dhangar), the "ajay-dhangar" part changes depending on the user. We handle this using **Params**. + +```javascript +// The colon (:) tells Express this part is a variable +app.get('/user/:username', (req, res) => { + const name = req.params.username; + res.send(`Viewing profile of: ${name}`); +}); +``` + +## 3. Query Strings + +Query strings are the key-value pairs you see after a `?` in a URL (e.g., `/search?club=cricket&sort=new`). These are optional and used for filtering or searching. + +```javascript title="server.js" +app.get('/search', (req, res) => { + const { club, sort } = req.query; + res.send(`Searching for ${club} sorted by ${sort}`); +}); +``` + +## 4. The Express Router + +To keep our code clean, we use `express.Router()` to group related routes into separate files. This is how we organize large projects at the Hub. + +### Step 1: Create a route file + +```javascript title="routes/userRoutes.js" +const express = require('express'); +const router = express.Router(); + +router.get('/profile', (req, res) => res.send('User Profile')); +router.get('/settings', (req, res) => res.send('User Settings')); + +module.exports = router; +``` + +### Step 2: Use it in your main server + +```javascript title="server.js" +const express = require('express'); +const app = express(); +const userRouter = require('./routes/userRoutes'); + +// All routes in userRouter will now start with /user +app.use('/user', userRouter); +``` + +## 5. Controllers: Separating Logic + +To be a professional "Master" developer, you shouldn't put your logic inside the route file. Instead, we use **Controllers**. + +* **Route file:** Defines the URL. +* **Controller file:** Contains the function logic. + +**Example Structure:** + +```javascript title="controllers/userController.js" +exports.getUserProfile = (req, res) => { + // Logic to fetch user from database would go here + res.json({ name: "Ajay", role: "Developer" }); +}; +``` + +Now, in your route file, you can import this controller: + +```javascript title="routes/userRoutes.js" +const userController = require('../controllers/userController'); +router.get('/profile', userController.getUserProfile); +``` + +## Practice: The Mini-Library API + +Try to create a router for a "Book" system: +1. Create a `bookRoutes.js` file. +2. Add a GET route for `/all` to see all books. +3. Add a GET route for `/:id` to see a specific book by its ID. +4. Link it to your `server.js` under the path `/api/books`. + +:::info HTTP Status Codes +When responding to a route, always send the correct status code. +* `200`: OK (Success) +* `201`: Created (Success after POST) +* `404`: Not Found +* `500`: Server Error + +```javascript title="bookRoutes.js" +const express = require('express'); +const router = express.Router(); + +router.get('/all', (req, res) => { + res.json([{ id: 1, title: "The Great Gatsby" }, { id: 2, title: "To Kill a Mockingbird" }]); +}); + +router.get('/:id', (req, res) => { + const bookId = req.params.id; + // In a real app, you'd fetch the book from the database + if (bookId == 1) { + res.json({ id: 1, title: "The Great Gatsby" }); + } else if (bookId == 2) { + res.json({ id: 2, title: "To Kill a Mockingbird" }); + } else { + res.status(404).send("Book not found!"); + } +}); + +module.exports = router; +``` +::: \ No newline at end of file