{"id":15110051,"url":"https://github.com/ashishranjan9585/nodejs","last_synced_at":"2026-01-19T12:33:12.245Z","repository":{"id":256877776,"uuid":"856449123","full_name":"ashishranjan9585/NodeJS","owner":"ashishranjan9585","description":"This repository all about to implement and practices NodeJS ","archived":false,"fork":false,"pushed_at":"2025-02-10T07:26:09.000Z","size":3621,"stargazers_count":1,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-02-10T08:27:04.028Z","etag":null,"topics":["expressjs","globalcache","javascript","jwt","middleware","mongoose","restful-api","zod"],"latest_commit_sha":null,"homepage":"","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/ashishranjan9585.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2024-09-12T15:38:44.000Z","updated_at":"2025-02-10T07:26:13.000Z","dependencies_parsed_at":null,"dependency_job_id":"31fde5e4-20a0-4245-9073-20083f47779a","html_url":"https://github.com/ashishranjan9585/NodeJS","commit_stats":null,"previous_names":["ashishranjan9585/nodejs"],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ashishranjan9585%2FNodeJS","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ashishranjan9585%2FNodeJS/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ashishranjan9585%2FNodeJS/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ashishranjan9585%2FNodeJS/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/ashishranjan9585","download_url":"https://codeload.github.com/ashishranjan9585/NodeJS/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":247364380,"owners_count":20927134,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["expressjs","globalcache","javascript","jwt","middleware","mongoose","restful-api","zod"],"created_at":"2024-09-25T23:40:28.934Z","updated_at":"2026-01-19T12:33:12.239Z","avatar_url":"https://github.com/ashishranjan9585.png","language":"JavaScript","readme":"# Content\n- [Some Async Concepts](#some-async-concepts)\n - [Promises](#promises) [Deep](#deep) \n - [Express](#express) \n - [HTTP Methods](#http-methods) \n - [Serving Routes](#serving-routes)\n\n# Some Asynchronous Concepts\n#### 1. `fetch()` Method\n- It is a Web API provided by the browser. `fetch()` is neither a library nor a module;\n- it is a native browser API provided by modern web browsers for making HTTP requests.It is commonly used to interact with web APIs and fetch data asynchronously.\n\nHere's a breakdown of what the `fetch()` method is and why it's used:\n\n#### What is the fetch() Method?\n   - The `fetch()` method is a built-in JavaScript function that simplifies making HTTP requests. It returns a Promise that resolves to the Response to that request, whether it is successful or not.\n\n#### Why is it Used?\n**1. Asynchronous Data Retrieval:**\n- The primary use of the `fetch()` method is to asynchronously retrieve data from a server. Asynchronous means that the code doesn't wait for the data to arrive before moving on. This is crucial for creating responsive and dynamic web applications.\n**2. Web API Interaction:**\n- Many web applications interact with external services or APIs to fetch data. The `fetch()` method simplifies the process of making HTTP requests to these APIs.\n**3. Promise-Based:**\n- The `fetch()` method returns a Promise, making it easy to work with asynchronous operations using the `.then()` and `.catch()` methods. This promotes cleaner and more readable code.\n\n#### Example 1:\n```javascript\nfetch('https://randomuser.me/api')\n    .then(response =\u003e {\n        return response.json(); // return a promise\n    })\n    .then(data =\u003e {\n        console.log(data);\n        // console.log(data.results[0].name);\n        // console.log(data.results[0].location);\n    })\n    .catch(error =\u003e {\n        console.log('Error:', error);\n    });\n  ```\nIn this example, we use `fetch()` to make a GET request to `'https://randomuser.me/api'`, handle the response, and then parse the JSON data. The `.then()` and `.catch()` methods allow us to handle the asynchronous flow and potential errors.\n\n#### Example 2:\n```javascript\n// 2.1 fetching Todos\nfunction fetchingTodo(){\n    fetch('https://sum-server.100xdevs.com/todos')\n    .then(async response =\u003e {\n        const json = await response.json();\n        console.log(json)\n    })\n}\n// fetchingTodo()\n\n// 2.2  Below Syntax is prefered\nasync function fetchingTodo2(){\n    const response = await fetch('https://sum-server.100xdevs.com/todos')\n    const json = await response.json();\n    console.log(json.todos.length)\n}\n// fetchingTodo2()\n```\n## 2. Callback Functions:\n**Definition:** A callback function is a function that is passed as an argument to another function and is executed after the completion of that function.\n\n#### Example:\n```javascript\nfunction fetchData(callback) {\n  // Simulating an asynchronous operation\n  setTimeout(() =\u003e {\n    const data = 'Hello, callback!';\n    callback(data);\n  }, 1000);\n}\n\n// Using the callback function\nfetchData(result =\u003e {\n  console.log(result);\n});\n```\n#### Example 2\n```javascript\n// Example 1\nfunction hello(a, b){\n    b();  // b is a callback function\n}\n//hello(1,2)  // Not a callback\nhello(1, function(){console.log(\"Callback Chala\")})  // Callback \n\n\n// Example 2\nfunction doSomeAsyncWork(x, y, callback){\n    setTimeout(function(){\n        callback(x, y);\n    }, 1000);\n}\ndoSomeAsyncWork(1, 2, function(x, y){\n    console.log(x + y);\n});\n\n\n// Example 3 - Bring users data and print name, email, and gender.\nfunction getUsersData(url, callback){\n    fetch(url)\n        .then(raw =\u003e raw.json())\n        .then(result =\u003e {\n            callback(result.results[0]);\n        });\n}\ngetUsersData('https://randomuser.me/api', function(user){\n    console.log(user.name.first, user.name.last);\n    console.log(user.email);\n    console.log(user.gender);\n});\n```\n**Relation to `fetch()`:** In older JavaScript code or libraries, callbacks were extensively used for handling asynchronous operations, such as handling the response in the .then() block of fetch().\n\n## 3. Promises:\n**Definition:** A Promise is an object representing the eventual completion or failure of an asynchronous operation. It is a more structured and readable way to handle asynchronous code compared to callbacks.\n\n#### Example:\n```javascript\nfunction fetchData() {\n  return new Promise((resolve, reject) =\u003e {\n    // Simulating an asynchronous operation\n    setTimeout(() =\u003e {\n      const success = true;\n      if (success) {\n        const data = 'Hello, Promise!';\n        resolve(data);\n      } else {\n        reject('Oops! Something went wrong.');\n      }\n    }, 1000);\n  });\n}\n\n// Using the Promise\nfetchData()\n  .then(result =\u003e {\n    console.log(result);\n  })\n  .catch(error =\u003e {\n    console.error(error);\n  });\n```\n**Relation to `fetch()`:** The `fetch()` method returns a Promise. We use `.then()` to handle the resolved value (successful response) and `.catch()` for handling errors.\n\n## 4. Async/Await:\n**Definition:** `async/await` is a syntactic sugar built on top of Promises, making asynchronous code more readable and easier to write.\n\n- `Async/Await` is a new way to write asynchronous code. It is built on top of promises, so it is also non-blocking.\n- It makes the code look like it is synchronous, but it is asynchronous.\n- `async` makes a function return a Promise, and the `await` makes a function wait for a Promise\n- The `await` keyword can only be used inside an `async `function.\n   If the function returns a value, the promise will be       resolved with the value.\n- If the function throws an exception, the promise will be rejected.\n#### Example 1:\n```javascript\nasync function fetchData(){\n    //  console log a will not be executed until the fetch is completed\n    let a = await fetch('https://randomuser.me/api')\n    a = await a.json();\n    console.log(a);\n}\nfetchData();\n```\n#### Example 2:\n```javascript\nasync function fetchData() {\n  return new Promise(resolve =\u003e {\n    // Simulating an asynchronous operation\n    setTimeout(() =\u003e {\n      const data = 'Hello, Async/Await!';\n      resolve(data);\n    }, 1000);\n  });\n}\n\n// Using async/await\nasync function fetchDataAndPrint() {\n  try {\n    const result = await fetchData();\n    console.log(result);\n  } catch (error) {\n    console.error(error);\n  }\n}\n\n// Invoking the async function\nfetchDataAndPrint();\n```\n## 5. Axios:\n- It does the same thing as fetch but slitly in the cleaner fastion. It is a popular JavaScript library used to make HTTP requests, and it can be used in both browser and Node.js environments. It is a promise-based library and developer-friendly.\n- To install - `npm install axios` / use CDN in HTML\n```javascript\nconst axios = require(\"axios\");\n\n// 1.\naxios\n  .get(`https://randomuser.me/api`)\n  .then((response) =\u003e {\n    console.log(response.data);\n  })\n  .catch((error) =\u003e {\n    console.log(\"Error:\", error);\n  });\n\n// 2. It automatically understand which data is coming back so no need to use .json\nasync function getaxios() {\n  const response = await axios.get(\"https://sum-server.100xdevs.com/todos\");\n  console.log(response.data);\n}\ngetaxios();\n```\n**Relation to `fetch()`:** In the context of `fetch()`,` async/await `provides a more synchronous-looking code structure when dealing with asynchronous operations, especially when handling responses.\n\n## Overall Relationship:\n- `Callbacks` were the traditional way of handling asynchronous code.\n- `Promises` introduced a more structured and readable way to   handle async operations.\n- `async/await` builds on top of Promises, offering a more  synchronous coding style, making asynchronous code look similar to synchronous code.\n#### Example Combining All:\n```javascript\nfunction fetchData(callback) {\n  setTimeout(() =\u003e {\n    const data = 'Hello, Callback!';\n    callback(data);\n  }, 1000);\n}\n\nfunction fetchDataPromise() {\n  return new Promise(resolve =\u003e {\n    setTimeout(() =\u003e {\n      const data = 'Hello, Promise!';\n      resolve(data);\n    }, 1000);\n  });\n}\n\nasync function fetchDataAsyncAwait() {\n  return new Promise(resolve =\u003e {\n    setTimeout(() =\u003e {\n      const data = 'Hello, Async/Await!';\n      resolve(data);\n    }, 1000);\n  });\n}\n\n// Using callback\nfetchData(result =\u003e {\n  console.log(result);\n\n  // Using Promise\n  fetchDataPromise()\n    .then(result =\u003e {\n      console.log(result);\n\n      // Using Async/Await\n      fetchDataAsyncAwait()\n        .then(result =\u003e {\n          console.log(result);\n        })\n        .catch(error =\u003e {\n          console.error(error);\n        });\n    })\n    .catch(error =\u003e {\n      console.error(error);\n    });\n});\n```\nIn this example, we've shown the use of callback, Promise, and Async/Await together. Async/Await provides a cleaner and more readable way to structure asynchronous code, especially when dealing with multiple async operations.\n\n## 5. Try Catch Blocks\nIn JavaScript and many other programming languages, a `try-catch` block is a mechanism for handling exceptions or errors in a structured way. This construct is crucial for writing robust and fault-tolerant code.\n\n#### Purpose:\n- The primary purpose of a `try-catch` block is to gracefully handle runtime errors or exceptions that may occur during the execution of a program. It allows developers to anticipate potential issues and implement a fallback strategy, preventing abrupt program termination.\n\n#### Syntax:\nThe basic syntax of a try-catch block is as follows:\n```javascript\ntry {\n  // Code that may throw an exception\n} catch (error) {\n  // Code to handle the exception\n}\n```\n- The `try` block encloses the code that might generate an exception.\n- If an exception occurs, the control is transferred to the catch block, where the error parameter holds information about the exception.\n#### How It Works:\n**1. Execution in the Try Block:**\n- Code inside the try block is executed sequentially.\n- If an exception occurs at any point, the normal flow of execution is interrupted.\n**2. Control Transfer to Catch Block:**\n- When an exception is thrown, control is transferred to the corresponding catch block.\n- The catch block is responsible for handling the exception.\n**3.Exception Handling:**\n- Inside the catch block, developers can implement error-handling logic.\n- They can log the error, display a user-friendly message, or take alternative actions to recover from the error.\n#### Example:\n```javascript\ntry {\n  // Code that may throw an exception\n  const result = 10 / 0; // Division by zero, will throw an exception\n  console.log(result); // This line won't be executed\n} catch (error) {\n  // Code to handle the exception\n  console.error('An error occurred:', error.message); // Output: An error occurred: Cannot divide by zero\n} finally {\n  // Code inside the finally block will execute regardless of whether an exception occurred or not\n  console.log('Finally block executed');\n}\n```\n- In this example, a division by zero operation inside the `try` block will throw an exception.\n- The control is then transferred to the `catch` block, where an error message is logged.\n- The `finally` block, if present, will always execute, providing an opportunity for cleanup or finalization tasks.\n# 1. Promises\nPromises are a way to handle asynchronous operations in JavaScript. They are easy to manage when dealing with multiple asynchronous operations where callbacks can create callback hell leading to unmanageable code.\n\n#### Key Characteristics of Promises:\n**1. Asynchronous Operations:**\n- Promises are commonly used to handle asynchronous operations, such as fetching data from a server, reading a file, or executing a timer.\n**2. States:**\nA promise can be in one of three states:\n- `Pending:` The initial state, before the promise is resolved or rejected.\n- `Fulfilled (Resolved):` The operation completed successfully, and the promise has a resulting value.\n- `Rejected:` There was an error during the operation, and the promise has a reason for the failure.\n**3.Chaining:**\n- Promises support chaining through the then method, allowing you to sequence asynchronous operations in a readable manner.\n**4.Error Handling:**\n- Promises have built-in error handling through the catch method, making it easier to manage and propagate errors in asynchronous code.\n#### Why Do We Need Promises?\n**1.Avoiding Callback Hell (Callback Pyramids):**\n\n- Promises help to mitigate the problem of callback hell, where nesting callbacks leads to unreadable and hard-to-maintain code.\n```javascript\n// Without Promises\nasyncOperation1((result1) =\u003e {\n  asyncOperation2(result1, (result2) =\u003e {\n    asyncOperation3(result2, (result3) =\u003e {\n      // ...\n    });\n  });\n});\n\n// With Promises\nasyncOperation1()\n  .then((result1) =\u003e asyncOperation2(result1))\n  .then((result2) =\u003e asyncOperation3(result2))\n  .then((result3) =\u003e {\n    // ...\n  });\n  ```\n**2.Sequential Execution of Asynchronous Code:**\n\n- Promises provide a clean way to execute asynchronous operations sequentially, improving code readability.\n```javascript\n// Without Promises\nasyncOperation1((result1) =\u003e {\n  asyncOperation2(result1, (result2) =\u003e {\n    asyncOperation3(result2, (result3) =\u003e {\n      // ...\n    });\n  });\n});\n\n// With Promises\nasyncOperation1()\n  .then((result1) =\u003e asyncOperation2(result1))\n  .then((result2) =\u003e asyncOperation3(result2))\n  .then((result3) =\u003e {\n    // ...\n  });\n  ```\n**3.Error Handling:**\n\n- Promises simplify error handling by providing a centralized catch block to handle errors for a sequence of asynchronous operations.\n```javascript\nasyncOperation1()\n  .then((result1) =\u003e asyncOperation2(result1))\n  .then((result2) =\u003e asyncOperation3(result2))\n  .catch((error) =\u003e {\n    console.error('An error occurred:', error);\n  });\n  ```\n**4.Promise.all for Parallel Execution:**\n\n- Promises offer the Promise.all method, allowing parallel execution of multiple asynchronous operations and waiting for all of them to complete.\n```javascript\nconst promise1 = asyncOperation1();\nconst promise2 = asyncOperation2();\n\nPromise.all([promise1, promise2])\n  .then((results) =\u003e {\n    const result1 = results[0];\n    const result2 = results[1];\n    // ...\n  })\n  .catch((error) =\u003e {\n    console.error('An error occurred:', error);\n  });\n  ```\nIn summary, promises provide a cleaner and more organized way to work with asynchronous code, making it easier to read, write, and maintain. They address common challenges associated with callback-based code and promote better error handling and sequential execution of asynchronous operations.\n\n#### Promises Basics:\n**1.Creating a Promise:**\n\n- A promise represents the eventual completion or failure of an asynchronous operation.\n- The Promise constructor takes a function with two parameters: resolve and reject.\n```javascript\nconst myPromise = new Promise((resolve, reject) =\u003e {\n  // Asynchronous operation goes here\n  // If successful, call resolve with the result\n  // If there's an error, call reject with the error\n});\n```\n**2.Resolving a Promise:**\n\n- Use the resolve function when the asynchronous operation is successful.\n```javascript\nconst successfulPromise = new Promise((resolve, reject) =\u003e {\n  setTimeout(() =\u003e {\n    resolve('Operation succeeded!');\n  }, 1000);\n});\n```\n**3.Rejecting a Promise:**\n\n- Use the reject function when there's an error during the asynchronous operation.\n```javascript\nconst failedPromise = new Promise((resolve, reject) =\u003e {\n  setTimeout(() =\u003e {\n    reject('Operation failed!');\n  }, 1000);\n});\n```\n#### Example:\n\n- Open html file in browser type mydata in the console and see the output.\n**HTML File**\n```html\n\u003c!DOCTYPE html\u003e\n\u003chtml lang=\"en\"\u003e\n\u003chead\u003e\n    \u003cmeta charset=\"UTF-8\"\u003e\n    \u003cmeta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"\u003e\n    \u003ctitle\u003eDocument\u003c/title\u003e\n\u003c/head\u003e\n\u003cbody\u003e\n    \u003ch1 style=\"text-align: center;\"\u003ePromises\u003c/h1\u003e\n\n    \u003cscript src=\"./05promise.js\"\u003e\u003c/script\u003e\n\u003c/body\u003e\n\u003c/html\u003e\n```\n**JS file**\n```javascript\n\nconst mydata = new Promise((resolve, reject) =\u003e {\n    // User lena bhja tha \n    fetch('https://randomuser.me/api')\n        .then(raw =\u003e raw.json())\n        .then(result =\u003e {\n            // Male hoga green button mtlab resolve\n            if(result.results[0].gender === \"male\")\n                resolve();\n            // Female hoga red button mtlab reject\n            else\n                reject();\n        })\n});\nconsole.log(mydata); // side stack - Promise { \u003cpending\u003e }\n\n\n// The below is my Task I can perform any task here after getting the users data from promise.\nmydata\n    .then(() =\u003e {\n        console.log(\"Green Button daba diya - for MALE\");\n    })\n    .catch(() =\u003e {\n        console.log(\"Red Button daba diya - for FEMALE\");\n    });\n ```   \n## Consuming Promises:\n**1. Using `then` and `catch`:**\n\n- The `then` method is used to handle the resolved value.\n- The `catch` method is used to handle errors.\n```javascript\nsuccessfulPromise\n  .then((result) =\u003e {\n    console.log(result); // Output: Operation succeeded!\n  })\n  .catch((error) =\u003e {\n    console.error(error); // This won't be called in this example\n  });\n  ```\n**2.Chaining Promises:**\n\n- Promises can be chained using `then`. Each `then` returns a new promise.\n```javascript\nsuccessfulPromise\n  .then((result) =\u003e {\n    console.log(result); // Output: Operation succeeded!\n    return 'New value';\n  })\n  .then((newValue) =\u003e {\n    console.log(newValue); // Output: New value\n  })\n  .catch((error) =\u003e {\n    console.error(error);\n  });\n  ```\n**3.Promise All:**\n\n- `Promise.all` is used to wait for multiple promises to complete.\n```javascript\nconst promise1 = Promise.resolve('One');\nconst promise2 = Promise.resolve('Two');\n\nPromise.all([promise1, promise2])\n  .then((values) =\u003e {\n    console.log(values); // Output: ['One', 'Two']\n  })\n  .catch((error) =\u003e {\n    console.error(error);\n  });\n  ```\nPromises are essential for handling asynchronous code in a clean and readable way, especially when working with features like fetching data from a server, handling events, or working with timers.\n# 2. Express\n**1.Express Framework:**\n\n- **Purpose:** Express is a web application framework for Node.js, designed to simplify the process of building web applications and APIs.\n- **Routing:** Express provides a powerful routing mechanism that allows you to define how your application responds to different HTTP requests (e.g., GET, POST).\n**3.HTTP Methods:**\n- `GET`: Used to retrieve data from the server. Typically used for reading information.\n- `POST`: Used to submit data to the server. Often used for creating or updating resources.\n- Other Methods (PUT, DELETE, etc.): Used for various purposes, such as updating or deleting resources.\n  \n**4.Routes:**\n\n**Definition:** \n- `Routes` define the paths in your application and the HTTP methods they respond to.\n- `Parameters`: Routes can have parameters that allow dynamic handling of different values.\n  \n**5.Request and Response Objects:**\n\n- **Request (req):** Represents the incoming HTTP request from the client. Contains information about the request, such as parameters, headers, and body.\n- **Response (res):** Represents the outgoing HTTP response to be sent back to the client. Allows you to send data, set headers, and more.\n- Listening and Ports:\n  - **Server Creation:** After defining routes and middleware, the Express application needs to be \"listened\" to for incoming requests.\n  - **Port:** The server listens on a specific port (e.g., `3000`) for incoming HTTP requests.\n```javascript\n//server.js\n// Import the express module\nconst express = require('express');\n\n// Create an instance of the express application\nconst app = express();\n\n// Define a route for the root URL (\"/\")\napp.get('/', (req, res) =\u003e {\n  res.send('Hello, this is the root/main route!');\n});\n\n// Define another route for \"/api\" with JSON response\napp.get('/api', (req, res) =\u003e {\n  res.json({ message: 'This is the API route.' });\n});\n\n// Define a route with URL parameters\napp.get('/greet/:name', (req, res) =\u003e {\n  const { name } = req.params;\n  res.send(`Hello, ${name}!`);\n});\n\n// Start the server on port 3000\nconst PORT = 3000;\napp.listen(PORT, () =\u003e {\n  console.log(`Server is running on \u003chttp://localhost\u003e:${PORT}`);\n});\n```\n## Run the server\n- `node server.js`\n- Visit `http://localhost:3000` in your browser, and you should see the response from the root route. You can also try accessing other defined routes (`/api`, `/greet/:name`).\n\n# 3. HTTPMethods\n`GET`, ``POST`, `PUT`, and `DELETE` are four HTTP methods used to interact with resources on a web server. They have different purposes, data submission methods, and impacts on server and browser behavior.\n\n#### GET:\n**1.Purpose:**\n- Used to request data from a specified resource.\n**2.Data Submission:**\n- Data is appended to the URL as query parameters.\n**3.Visibility:**\n- Parameters are visible in the URL.\n**4.Caching:**\n- Requests can be cached by the browser, and URLs can be bookmarked.\n**5.Examples:**\n- Fetching a webpage, retrieving search results.\n#### POST:\n**1.Purpose:**\n- Used to submit data to be processed to a specified resource.\n**2.Data Submission:**\n- Data is sent in the request body.\n**3.Visibility:**\n- Parameters are not visible in the URL.\n**4.Caching:**\n- Requests are not cached, and URLs cannot be bookmarked.\n**5.Examples:**\n- Submitting a form, uploading a file.\n#### PUT:\n**1.Purpose:**\n- Used to update a resource or create a new resource if it doesn't exist.\n**2.Data Submission:**\n- Similar to POST, data is sent in the request body.\n**3.Visibility:**\n- Parameters are not visible in the URL.\n**4.Caching:**\n- Similar to POST, requests are not cached, and URLs cannot be bookmarked.\n**5.Examples:**\n- Updating a user's profile.\n#### DELETE:\n**1.Purpose:**\n- Used to delete a specified resource.\n**2.Data Submission:**\n- No data is typically sent with the request.\n**3.Visibility:**\n- Parameters are not visible in the URL.\n**4.Caching:**\n- Similar to POST and PUT, requests are not cached, and URLs cannot be bookmarked.\n**5.Examples:**\n- Deleting a user account.\n#### When to Use Each:\n- **GET:** Use for safe and idempotent operations, such as retrieving data.\n- **POST:** Use for non-idempotent operations, like submitting data.\n- **PUT:** Use to update or create resources.\n- **DELETE:** Use to delete resources.\nThe choice of method depends on the operation you want to perform and the desired behavior for interacting with the server.\n\n## How to handle GET requests\nHandling `GET` requests in an Express.js application involves defining routes that respond to GET HTTP requests. Here's a basic example of handling a GET request in an Express.js application:\n```javascript\nconst express = require('express');\nconst app = express();\nconst port = 3000;\n\n// Define a simple GET route\napp.get('/', (req, res) =\u003e {\n  res.send('Hello, this is a GET request!');\n});\n\n// Define a route with a parameter\napp.get('/greet/:name', (req, res) =\u003e {\n  const { name } = req.params;\n  res.send(`Hello, ${name}!`);\n});\n\n// Start the server\napp.listen(port, () =\u003e {\n  console.log(`Server is running on \u003chttp://localhost\u003e:${port}`);\n});\n```\nIn this example:\n\n1. We create an instance of the Express application using `express()`.\n2. We define a simple GET route for the root URL (`'/'`) that responds with a message.\n3. We define another GET route with a parameter (`'/greet/:name'`) that responds with a personalized greeting based on the parameter.\n4. We start the server with `app.listen` on port 3000.\n\nWhen you run this script (`node filename.js`) and visit `http://localhost:3000` in your browser, you should see the response from the root route. Additionally, visiting `http://localhost:3000/greet/Ashish` should display a personalized greeting for the name \"Ashish.\"\n\nThis is a basic example, and in a real-world application, you would likely have more complex routes and logic. Express provides a flexible and powerful routing system, allowing you to handle different HTTP methods, route parameters, query parameters, and more.\n\n## How to handle POST request\nWhen building web applications, it's common to use HTTP POST requests to send data from the client (e.g., a form submission) to the server. In Express.js, handling POST requests involves using middleware to parse the incoming data and defining route handlers to process the data accordingly.\n\n## Middleware for Parsing JSON and Form Data:\nBefore handling `POST` requests, it's important to include middleware to parse the incoming data. Express provides built-in middleware for handling JSON and form data. Add the following middleware to your Express app:\n```javascript\n// Middleware to parse JSON and form data\napp.use(express.json());\napp.use(express.urlencoded({ extended: true }));\n```\n## Handling a POST Request:\n```javascript\n// In-memory array to store text content\nconst textContent = [];\n\n// Route to handle POST requests for adding text content\napp.post('/add-content', (req, res) =\u003e {\n  // Extract text content from the request body\n  const newContent = req.body.content;\n\n  // Validate the content (you might want to add more robust validation)\n  if (!newContent) {\n\t\t// if there is an error it will send the code 400 and an error\n    return res.status(400).json({ error: 'Content is required' });\n  }\n\n  // Add the content to the in-memory array\n  textContent.push(newContent);\n\n  // Respond with a success message\n  res.status(201).json({ message: 'Content added successfully' });\n});\n```\n## Handling PUT and DELETE Requests\n`PUT`and `DELETE` requests are used to update and delete resources on the server, respectively. In Express.js, you can handle these requests similarly to POST requests by defining appropriate routes and route handlers.\n```javascript\n// Route to handle PUT requests for updating a resource\napp.put('/update-resource/:id', (req, res) =\u003e {\n  const resourceId = req.params.id;\n  // Process the update and send a response\n});\n\n// Route to handle DELETE requests for deleting a resource\napp.delete('/delete-resource/:id', (req, res) =\u003e {\n  const resourceId = req.params.id;\n  // Process the deletion and send a response\n});\n```\nExpress provides a flexible and powerful routing system, allowing you to handle various HTTP methods and implement complex application logic easily.\n\n# 3. Response Object\n## Sending response back to Client\nIn an Express.js application, you send a response back to the client using the res (response) object. The res object provides various methods to send different types of responses, such as text, JSON, HTML, and more. Here are some common ways to send responses back to the client:\n\n**1.Sending Plain Text:**\n\n- Use the `res.`send method to send plain text.\n```javascript code\napp.get('/', (req, res) =\u003e {\n  res.send('Hello, this is a plain text response!');\n});\n```\n**2.Sending JSON:**\n\n- Use the `res.json` method to send a JSON response.\n```javascript code\napp.get('/api/data', (req, res) =\u003e {\n  const data = { message: 'This is a JSON response.' };\n  res.json(data);\n});\n```\n**3.Sending HTML:**\n\n- Use the `res.send` method to send HTML content.\n```javascript code\napp.get('/html', (req, res) =\u003e {\n  const htmlContent = '\u003ch1\u003eThis is an HTML response\u003c/h1\u003e';\n  res.send(htmlContent);\n});\n```\n**3.Redirecting:**\n\n- Use the `res.redirect` method to redirect the client to a different URL.\n```javascript code\napp.get('/redirect', (req, res) =\u003e {\n  res.redirect('/new-location');\n});\n```\n**4.Sending Status Codes:**\n\n- Use the `res.status` method to set the HTTP status code.\n```javascript code\napp.get('/not-found', (req, res) =\u003e {\n  res.status(404).send('Page not found');\n});\n```\n**5.Sending Files:**\n\nUse the `res.sendFile` method to send files.\n```javascript code\nconst path = require('path');\n\napp.get('/file', (req, res) =\u003e {\n  const filePath = path.join(__dirname, 'files', 'example.txt');\n  res.sendFile(filePath);\n});\n```\n\nThese examples showcase various ways to send responses back to the client based on different scenarios. The res object provides a versatile set of methods to handle a wide range of response types. Depending on the use case, you can choose the appropriate method to send the desired response to the client.\n\n# 4. ServingRoutes\nHow to serve different routes\nUse the app object to define routes for different URLs. Routes are defined using HTTP methods (such as `GET`, `POST`, `PUT`, `DELETE`, etc.) and specify a callback function that gets executed when a request matches the specified URL and method.\n```javascript\nconst express = require('express');\nconst app = express();\nconst port = 3000;\n\n// get route\napp.get('/', (req, res) =\u003e {\n  res.send('Hello from GET route!');\n});\n\n// post route\napp.post('/add', (req, res) =\u003e {\n  res.send('Hello from POST route!');\n});\n\n// PUT route - updation\napp.put('/put/:id', (req, res) =\u003e {\n  res.send('Hello from PUT route!');\n});\n\n//DELETE route \napp.delete('/delete/:id', (req, res) =\u003e {\n  res.send('Hello from DELETE route!');\n});\n\napp.listen(port, () =\u003e {\n  console.log(`Server is running on \u003chttp://localhost\u003e:${port}`);\n});\n```\n# 5. Understanding ENV\n## How to start `PORT` on an env variable\n**Install dotenv package**\n- Install the `dotenv` package using `npm`. This package allows you to load environment variables from a file.\n```\nnpm install dotenv\n```\n**Create a .env File:**\n- Create a file named `.env` in the root of your project. This file will contain your environment variables. Add a variable for the port, for example:\n```\nPORT=3000\n```\n**Load Environment Variables in Your Express App:**\n- In your main Express application file (**e.g., app.js or index.js**), load the environment variables using `dotenv.` Add the following lines at the top of your file:\n```javascript\n  require('dotenv').config();\n  ```\n**Use the PORT Environment Variable:**\n```javascript\nconst express = require('express');\nconst app = express();\nconst port = process.env.PORT || 3000;\n\n// Rest of your Express app code...\n\napp.listen(port, () =\u003e {\n  console.log(`Server is running on \u003chttp://localhost\u003e:${port}`);\n});\n```\n**Run Your Express App:**\n```\nnode app.js\n```\n# 6. JSON\n## How to send JSON response\nIn an Express.js application, you can send a JSON response using the `res.json()` method. This method automatically sets the appropriate Content-Type header to `application/json` and sends the JSON-formatted response to the client.\n```javascript\nconst express = require('express');\nconst app = express();\nconst port = 3000;\n\napp.get('/get-json', (req, res) =\u003e {\n  // Create an object to be sent as JSON\n  const responseData = {\n    message: 'This is a JSON response',\n    data: {\n      key1: 'value1',\n      key2: 'value2',\n    },\n  };\n\n  // Send the JSON response\n  res.json(responseData);\n});\n\napp.listen(port, () =\u003e {\n  console.log(`Server is running on \u003chttp://localhost\u003e:${port}`);\n});\n```\n\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fashishranjan9585%2Fnodejs","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fashishranjan9585%2Fnodejs","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fashishranjan9585%2Fnodejs/lists"}