0% found this document useful (0 votes)
12 views14 pages

Node.js Server Setup and Express API Guide

The document provides a comprehensive guide on creating a web server using Node.js and Express.js, detailing how to handle various HTTP requests and manage user data through REST APIs. It explains the structure of URLs, the use of middleware, response headers, and how to connect Node.js applications to MongoDB. Additionally, it covers the differences between GET and other HTTP methods like POST, PUT, and PATCH, along with practical code examples for each functionality.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views14 pages

Node.js Server Setup and Express API Guide

The document provides a comprehensive guide on creating a web server using Node.js and Express.js, detailing how to handle various HTTP requests and manage user data through REST APIs. It explains the structure of URLs, the use of middleware, response headers, and how to connect Node.js applications to MongoDB. Additionally, it covers the differences between GET and other HTTP methods like POST, PUT, and PATCH, along with practical code examples for each functionality.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Node JS Notes

Create own server That listen on port 8000


Code-
[Link]("Hey I am Bappa");
const http=require("http");
const fs=require("fs");

const myServer=[Link]((req,res)=>{
[Link]("./[Link]",`${[Link]()}: New Request Received\n`,(err,data)=>{
[Link]("Success");
});
switch([Link])
{
case "/":
[Link]("This is Homepage");
break;
case "/about":
[Link]("This is about page");
break;
default:
[Link]("Homepage");
}
});

[Link](8000,()=>{
[Link]("Server Started");
});
createServer ka use hum apna khud ka web server banane ke liye karte hain, taaki hum
requests le sake aur responses bhej sake.
URL- UNIFORM RESOURCE LOCATOR
[Link]

Part Name Explanation


https Protocol Kaunsa rule follow kare: HTTP ya HTTPS
[Link] Host/Domain Server ka naam ya address
:8080 Port Optional port (default hota hai 80 for HTTP, 443 for HTTPS)

/home/about Path Web page ka location on server


?user=123 Query String Extra data send karne ke liye (key=value)
#top Fragment Page ke kisi part ko point karta hai (scroll to section)

Code-
const http = require("http");
const fs = require("fs");
const url = require("url");

const myServer = [Link]((req, res) => {


if ([Link] === "/[Link]") return [Link]();

const log = `${[Link]()}: ${[Link]} New Req Received\n`;

const myUrl = [Link]([Link], true);


[Link](myUrl);

[Link]("[Link]", log, (err) => {


if (err) {
return [Link]("Error writing log");
}
switch ([Link]) {
case "/":
[Link]("HomePage");
break;

case "/about":
const username = [Link];
[Link](`Hi, ${username}`);
break;

case "/search":
const search = [Link].search_query;
[Link]("Here are your results for " + search);
break;

default:
[Link]("404 Not Found");
}
});
});

[Link](8000, () => {
[Link]("Server listening on port 8000");
});

This code creates a simple web server using [Link]. When someone visits the server (like
opening a webpage), it checks the URL they used. The server saves a log of that request in a
file called [Link]. Then, it looks at what the user is trying to open:
 If they go to /, it shows “HomePage”.
 If they go to /about?myname=Ravi, it reads the name and says “Hi, Ravi”.
 If they go to /search?search_query=nodejs, it shows “Here are your results for
nodejs”.
 If the URL doesn’t match any of these, it shows “404 Not Found”.
The server runs on port 8000, and you can test it by visiting [Link] in your
browser.

Express JS
Syntax-
app. method (“Path”, ”Handler Fun”)
Code-
const express = require("express");
// const http = require("http"); no needed becoz in express() internally http module is
existing

const app = express();

[Link]("/", (req, res) => {


[Link]("This is homepage");
});

[Link]("/about", (req, res) => {


return [Link](`Hello ${[Link]}`);
});
[Link](8000,()=>[Link](“Listening”));
or
// const server = [Link](app); //
<-- this is like saying: handle all req/res with app it is like function that handle any url means
extract only path like /about ,/contact-us
// [Link](8000, () => [Link]("Listening on 8000"));

Concept Explanation

express() Creates a function to handle requests and responses


Concept Explanation

[Link](app) Creates an HTTP server that uses the express app to respond

Why pass app? Because app is a handler function that knows how to respond to different URLs

Code Explaination on REST API

This code snippet is written in [Link] with [Link], and it defines a route to handle API
requests for users. Here's a breakdown in simple terms:

📌 Full Explanation:
.route("/api/users/:id")
 This sets up a dynamic route. The :id means we can send requests like /api/users/5.

1. GET Request (Read User Data):


.get((req, res) => {
const id = Number([Link]);
const user = [Link]((user) => [Link] === id);
return [Link](user);
})
 [Link]: Gets the ID from the URL (like /api/users/2 will give 2).
 Number(...): Converts it to a number.
 [Link](...): Searches for the user in the users array whose id matches.
 [Link](user): Sends the user data back in JSON format.

2. PATCH Request (Edit or Update User):


.patch((req, res) => {
// Edit user with id
return [Link]({ status: "Pending" });
})
 This part is not yet implemented; it just sends a JSON response with status
"Pending" for now.

✅ Summary in Simple Words:


 GET /api/users/:id → finds and returns user by ID.
 PATCH /api/users/:id → placeholder to update a user, not functional yet.

If you want, I can help you implement the .patch() part too. Let me know, bhai.
const id = Number([Link]); // "5" -> 5
Is line ka kaam: URL se id nikaalna aur usko number mein convert karna.
REST API Methods
Code ---
const express = require("express");
const app = express();
const PORT = 3000;

// Middleware to parse JSON


[Link]([Link]());

// Dummy data
let users = [
{ id: 1, name: "Sarthak" },
{ id: 2, name: "Rohit" }
];

// ✅ POST - Add new user


[Link]("/api/users", (req, res) => {
const newUser = [Link];
[Link](newUser);
[Link](201).json({ message: "User added", user: newUser });
});

// ✅ PUT - Full update of a user


[Link]("/api/users/:id", (req, res) => {
const id = Number([Link]);
const index = [Link]((user) => [Link] === id);

if (index === -1) {


return [Link](404).json({ message: "User not found" });
}

users[index] = [Link]; // full replacement


[Link]({ message: "User fully updated", user: users[index] });
});

// ✅ DELETE - Remove a user


[Link]("/api/users/:id", (req, res) => {
const id = Number([Link]);
const initialLength = [Link];
users = [Link]((user) => [Link] !== id);

if ([Link] === initialLength) {


return [Link](404).json({ message: "User not found" });
}

[Link]({ message: "User deleted" });


});
// ✅ GET - (for checking)
[Link]("/api/users", (req, res) => {
[Link](users);
});

// ✅ Start server
[Link](PORT, () => {
[Link](`Server running on [Link]
});

Explaination

"POST, PATCH, PUT bhejne ke liye Postman, frontend app ya curl hi kyu chahiye?"
Chal ekdum simple example aur reason ke saath samjhaata hoon:

✅ 1. Browser se sirf GET request asaan hoti hai


Kyun?
 Jab tu browser mein likhta hai:
 [Link]
Toh browser automatically GET request bhejta hai.
 Lekin browser mein koi button nahi hota "POST request bhejne ka" direct URL bar
se.

✅ 2. POST, PATCH, PUT mein body bhejna padta hai


Example:
POST request mein tu ye bhejta hai:
{
"name": "Sarthak",
"age": 22
}
Is type ka data bhejne ke liye interface chahiye, jo body set kar sake.

✅ 3. Isiliye use karte hain Postman / Frontend / curl


Tool Kaam kya karta hai?

Postman GUI tool hai, jisme tu method select kar sakta hai (POST, PUT...) aur body bhej sakta hai

Frontend Tu frontend app (React, HTML+JS) bana ke JS se request bhejta hai

curl Command-line tool hai, jisme tu terminal se request bhejta hai (useful for testing)

🔍 Example with Postman:


1. Method: POST
2. URL: [Link]
3. Body tab → raw → JSON:
{
"name": "Sarthak"
}
Yeh browser se nahi ho sakta, par Postman easily karta hai.

🔥 Summary:
GET request easily
Browser
karta hai ✅

POST, PUT, PATCH request body bhejte hain → browser mein


support nahi hai directly ❌

Isiliye tu use karta hai Postman, curl, ya frontend app ✅


Express MiddleWare----

✅ What is next() in Express?


In Express, next() is a function that tells the app to:
"Go to the next middleware or the next route."
It’s used inside middleware to continue the flow.

📦 Syntax Example:
[Link]((req, res, next) => {
[Link]("Step 1: This is middleware");
next(); // go to next step
});
Without next(), the request would stop and never reach your final route.

🔁 Use Case:
You can add many middlewares:
Code-

[Link]((req, res, next) => {


[Link]("1st");
next();
});

[Link]((req, res, next) => {


[Link]("2nd");
next();
});

[Link]("/", (req, res) => {


[Link]("Final response");
});
Output:
1st
2nd
Final response
✅ Summary:
Term Meaning

next() Tells Express to go to the next step

Without it Request gets stuck, never reaches route

Use it in Middleware functions

Let me know if you want me to show this with a real working mini app 👨‍💻

 ✅ What are Response Headers?

Response headers give extra info about the response sent by the server — like:
 What type of data it is
 Can it be cached?
 Is it allowed in other domains? (CORS)
 Custom messages
 Cookies, etc.

🧾 Common Response Headers (with meaning):


Header Name What it Means

Content-Type Format of the data (e.g., JSON, HTML, text)

Content-Length Size of the response body (in bytes)

Cache-Control Controls browser cache (store or not)

Set-Cookie Sends cookies to client

Access-Control-Allow-Origin Controls CORS (allow access from other domains)

X-Powered-By Shows tech used (like Express, [Link])

Date Date and time when the response was sent

ETag Used for caching and versioning of data


Header Name What it Means

Connection Controls connection type (keep-alive or close)

🧪 Example (in Postman or browser):


When you hit an API, response headers might look like:
HTTP/1.1 200 OK
Content-Type: application/json
Content-Length: 42
X-Powered-By: Express
Access-Control-Allow-Origin: *
Date: Fri, 14 Jun 2025 07:00:00 GMT

🛠 Set Custom Response Headers in Express:


[Link]("/info", (req, res) => {
[Link]({
"Content-Type": "application/json",
"X-Custom-Header": "SarthakAPI",
"Access-Control-Allow-Origin": "*"
});
[Link]([Link]({ message: "Hello from server" }));
});

✅ Summary
Header Use

Content-Type Tells format (JSON, HTML, etc.)

Set-Cookie Sends cookies

X-* Custom or tech info

Access-Control-Allow-Origin For cross-domain requests

Cache-Control Tells browser to cache or not


Let me know bro if you want to see how to read headers on the client side too 👇 (like in
frontend JavaScript).

 Node JS Connect with MongoDB


const { MongoClient } = require("mongodb"); // Step 1: Import

const uri = "mongodb://[Link]:27017"; // Step 2: MongoDB ka local address


const client = new MongoClient(uri); // Step 3: Client banaya

let usersCollection; // Step 4: Collection ka reference store hoga

// Step 5: Function to connect to MongoDB


async function connectDB() {
try {
await [Link](); // Step 6: Connect with MongoDB
const db = [Link]("mydb"); // Step 7: Database banega ya mil jayega
usersCollection = [Link]("users"); // Step 8: Collection banega ya mil jayega
[Link]("✅ MongoDB Connected");
} catch (err) {
[Link]("❌ MongoDB Connection Failed", err);
}
}

connectDB(); // Step 9: Function ko call kiya


Bhai 💡 ekdum simple bhaasha mein:

 ✅ MongoClient kya hai?


MongoClient ek gatekeeper hai jo tera [Link] backend ko MongoDB database se connect
karta hai.

🏪 Real-Life Example Se Soch:


Soch MongoDB ek godown (warehouse) hai jahan tera data pada hai.
 Tu ([Link] app) us godown me data rakhne (insert), lane (fetch), delete ya update
karne ja raha hai.
 Lekin bina gatekeeper ke tu godown me ghus nahi sakta 😄
👉 MongoClient wahi gatekeeper hai
Jo bolta hai:
“OK bhai, tu allowed hai — andar aa ja, database se kaam kar le!”

🔧 Technical Definition:
MongoClient is a class from the mongodb [Link] driver
It helps you connect, communicate, and interact with MongoDB database from your code.

📦 Jab Tu MongoClient Use Karta Hai:


1. MongoDB se connect karta hai
const client = new MongoClient("mongodb://[Link]:27017");
2. Database choose karta hai
const db = [Link]("mydb");
3. Collection (table) access karta hai
const users = [Link]("users");
4. Data insert/update/find/delete karta hai
await [Link]({ name: "Sarthak" });

🔁 Short Summary:
Cheez Matlab

MongoClient MongoDB ke saath connection banata hai

Bina iske Tu MongoDB me data nahi daal sakta

Driver ka part mongodb naam ke package ka class hai

Soch le "MongoClient = connection key + gatekeeper" 🔑

Agar tu chahe toh main full working backend example MongoClient ke saath bana ke deta
hoon — bol bhai 🙌

You might also like