Initial Installation

<aside> 💬

  1. npm install express@latest
  2. npm install mongoose@latest
  3. npm install ejs@latest
  4. npm install --save-dev nodemon </aside>

Connect to DB

<aside> 💬

const express = require("express");
const mongoose = require("mongoose");

mongoose
  .connect(
    "mongodb+srv://osmantaher:Osman2005@nodejs.lmbxfvs.mongodb.net/?appName=Nodejs",
  )
  .then(() => {
    console.log("Seccuse to connect ");
  })
  .catch((error) => {
    console.log("Error to connect DB", error);
  });

</aside>


Path root

<aside> 💬

const app = express();
app.use(express.json());
app.get("/", (req, res) => {
  res.send("Hello Osman !");
});
app.get("/hello", (req, res) => {
  res.send("Hello !!!");
});

</aside>


1. URL Parameters (req.params)

<aside> 💬

This method is used when the data is part of the URL path itself. It is ideal for identifying specific resources (like an ID or, in your case, numbers for a calculation).

How it works:

app.get("/sum/:num1/:num2", (req, res) => {
  const n1 = Number(req.params.num1);
  const n2 = Number(req.params.num2);
  res.send(`sum ${n1 + n2}`);
});

</aside>


2. Alternative: Query Parameters (req.query)

<aside> 💬

There is another very common way to send data through a GET request without changing the route structure. This is called Query Strings.

app.get("/sum", (req, res) => {
const n1 = Number(req.query.num1);
const n2 = Number(req.query.num2);
res.send(sum is: ${n1 + n2});
});

How to test in Postman:

Instead of putting numbers in the path, you add them after a question mark: http://localhost:3000/sum?num1=5&num2=10


3. Request Body (req.body)

<aside> 💬

This method is used with POST requests to send data securely and in large amounts. The data is hidden within the request body, not shown in the URL.

app.post("/sum", (req, res) => {
  const { num1, num2 } = req.body; // Destructuring data
  const result = Number(num1) + Number(num2);
  res.send({ sum: result }); // Sending response as JSON
});

How to test in Postman:

  1. Change the request method from GET to POST.
  2. Enter the URL: http://localhost:3000/sum.
  3. Go to the Body tab.
  4. Select raw and choose JSON from the dropdown menu.
  5. Write your data like this: { "num1": 20 , "num2": 30 } . </aside>

Ways to Send a Response in Express

<aside> 💬

1. Sending HTML Strings (res.send)

JavaScript

res.send("<h1 style='color:skyblue'>Osman Taher</h1>");

2. Sending Static Files (res.sendFile)

JavaScript

res.sendFile(__dirname + "/views/index.html");

3. Rendering Dynamic Templates (res.render)

JavaScript

res.render("index.ejs", { name: "Omr" });

Method Usage Data Type Flexibility
res.send() res.send("<h1>Hello</h1>") String/HTML Very Low
res.sendFile() res.sendFile(path) Static File Low
res.render() res.render("page", {data}) Dynamic Template Very High
</aside>