Initial Installation
<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).
:num1 and :num2 are placeholders in the URL.GET request to: http://localhost:3000/sum/5/10.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});
});
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:
GET to POST.http://localhost:3000/sum.Ways to Send a Response in Express
<aside> 💬
res.send)JavaScript
res.send("<h1 style='color:skyblue'>Osman Taher</h1>");
res.sendFile)JavaScript
res.sendFile(__dirname + "/views/index.html");
__dirname: A Node.js variable that gives you the absolute path to the folder where your script is running.res.render)JavaScript
res.render("index.ejs", { name: "Omr" });
{ name: "Omr" } to the HTML.index.ejs, you can now use <%= name %> to display "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> |