# Lesson 1: Key Concepts of NodeJS and Express for Backend Web Development

## **Introduction to Node.js:**

* **What is Node.js?** An open-source, cross-platform JavaScript runtime environment that executes JavaScript code outside a browser.
* **Why Node.js for Backend?**
  * Non-blocking, event-driven architecture for efficient performance.
  * Single language (JavaScript) for both frontend and backend.
  * Large ecosystem via npm (Node Package Manager).

**Core Concepts in Node.js:**

* **Event Loop:** Handles asynchronous operations.
* **Modules:** Built-in (fs, http) and custom modules.
* **npm Packages:** Managing dependencies using `package.json`.

### **Introduction to Express:**

* **What is Express?** A minimal and flexible Node.js web application framework.
* **Features:**
  * Simplifies routing and middleware management.
  * Facilitates REST API development.
  * Easily integrates with databases.

### **2. Building Web Applications with Express:**

**Setting Up an Express Application:**

1. **Initialize Node Project:**

   ```bash
   mkdir express-app && cd express-app
   npm init -y
   npm install express
   ```
2. **Create a Basic Server:**
   * Create `index.js`:

     ```javascript
     const express = require('express');
     const app = express();
     const PORT = 3000;

     app.get('/', (req, res) => {
       res.send('Hello, World!');
     });

     app.listen(PORT, () => {
       console.log(`Server running on http://localhost:${PORT}`);
     });
     ```
3. **Run the Server:**

   ```bash
   node index.js
   ```

   * Visit `http://localhost:3000` in your browser to see "Hello, World!"

### **Routing in Express:**

* **Define Routes:**

  ```javascript
  app.get('/about', (req, res) => {
    res.send('About Page');
  });

  app.post('/contact', (req, res) => {
    res.send('Contact Form Submitted');
  });
  ```

### **Middleware in Express:**

* **Using Middleware:**

  ```javascript
  app.use(express.json());  // To parse JSON bodies
  app.use((req, res, next) => {
    console.log(`${req.method} request for '${req.url}'`);
    next();
  });
  ```

### **3. REST API Development with Express:**

#### **Create a Simple REST API:**

1. **Sample Data:**

   ```javascript
   let users = [
     { id: 1, name: 'Alice' },
     { id: 2, name: 'Bob' },
   ];
   ```
2. **CRUD Operations:**
   * **GET (Retrieve All Users):**

     ```javascript
     app.get('/users', (req, res) => {
       res.json(users);
     });
     ```
   * **GET (Retrieve Single User):**

     ```javascript
     app.get('/users/:id', (req, res) => {
       const user = users.find(u => u.id == req.params.id);
       if (user) res.json(user);
       else res.status(404).send('User not found');
     });
     ```
   * **POST (Add New User):**

     ```javascript
     app.post('/users', (req, res) => {
       const newUser = { id: users.length + 1, ...req.body };
       users.push(newUser);
       res.status(201).json(newUser);
     });
     ```
   * **PUT (Update User):**

     ```javascript
     app.put('/users/:id', (req, res) => {
       const index = users.findIndex(u => u.id == req.params.id);
       if (index !== -1) {
         users[index] = { id: parseInt(req.params.id), ...req.body };
         res.json(users[index]);
       } else res.status(404).send('User not found');
     });
     ```
   * **DELETE (Remove User):**

     ```javascript
     app.delete('/users/:id', (req, res) => {
       users = users.filter(u => u.id != req.params.id);
       res.status(204).send();
     });
     ```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://reactjs.koida.tech/backend-frameworks-next.js/lesson-1-key-concepts-of-nodejs-and-express-for-backend-web-development.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
