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

Backend

The document discusses the use of proxies in Vite for frontend development to avoid CORS issues when connecting to a backend server. It explains how to set up a proxy in a React project and highlights the benefits of using a proxy during development. Additionally, it covers various backend concepts such as Mongoose for database management, bcrypt for password hashing, and JWT for user authentication.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views16 pages

Backend

The document discusses the use of proxies in Vite for frontend development to avoid CORS issues when connecting to a backend server. It explains how to set up a proxy in a React project and highlights the benefits of using a proxy during development. Additionally, it covers various backend concepts such as Mongoose for database management, bcrypt for password hashing, and JWT for user authentication.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

We can create /edit script data

the difference is what type of js u used


module or normal js
Great question, Rajveer!

🔍 Why do we use proxy in Vite (or any frontend dev server)?


When you develop a frontend app (like with Vite + React) and you have a backend server
running separately (like Express on port 3000), the browser won’t allow your frontend to
call the backend directly due to CORS (Cross-Origin Resource Sharing) restrictions.

🧰 That's where proxy comes in:


Vite runs your frontend on (for example) http://localhost:5173, and your backend
runs on http://localhost:3000.

So, if your React app does:

js
CopyEdit
axios.get('/api/user')
Without a proxy, that would hit:

bash

❌ (No backend here)


CopyEdit
http://localhost:5173/api/user

But with this proxy setting:

js
CopyEdit
proxy: {
'/api': 'http://localhost:3000'
}

Vite intercepts the /api request, forwards it to:

bash


CopyEdit
http://localhost:3000/api/user

Your React app can pretend it's calling its own server, while Vite quietly forwards the
request to your real backend.

✅ Benefits of using proxy:


Benefit Description

✅ Avoids CORS issues You don’t need to enable CORS on the backend during
development

✅ Keeps frontend code You can write /api/something instead of hardcoding


clean full URLs

✅ Smoother local No need to run both frontend & backend on the same
development port
CORS Policy – Handling Cross-Origin Requests in Node.js & Express 🚀
🔹 What is CORS?
CORS (Cross-Origin Resource Sharing) is a security feature in browsers that blocks
requests from different origins.

🔴 Example of a CORS Error:​


If your frontend (React) is running on http://localhost:3000 and your backend
(Express) is on http://localhost:5000, the browser will block API calls due to CORS
policy restrictions.

And u can allow some url accrodin to uhh also


Why Use a Proxy in React? 🚀
A proxy in React helps avoid CORS issues when the frontend (React - localhost:3000)
communicates with the backend (Express - localhost:5000).

🔹 How to Use Proxy?


Add this in package.json (React project):​

json​
CopyEdit​
"proxy": "http://localhost:5000"

1.​

Use API calls without full URL:​



javascript​
CopyEdit​
axios.get('/api/data') // Auto-forwards to
http://localhost:5000/api/data

2.​
3.​ ✅ No need to handle CORS in the backend manually.​
4.​ ✅ Only needed during development (not in production).​

Would you like to see a React + Express setup example?

Mongoose Backend Recap (Short & Sweet)

1.​ ✅ Schemas — Define data structure using mongoose.Schema.​


2.​ 🔗 References — Connect models using:​

js

CopyEdit

type: mongoose.Schema.Types.ObjectId, ref: 'ModelName'

3.​ 📚 Populate — Fetch full data of referenced docs:​


js

CopyEdit

.populate('field.ref')

4.​ 📦 Arrays of References — For storing multiple items (e.g., doctor in many
hospitals):​

js

CopyEdit

hospital: ObjectId,

hoursSpent: Number

5.​ ♻️ Sub-Schema Reuse — Create reusable mini schemas and embed:​


js

CopyEdit

const DoctorWorkSchema = new Schema({ doctor, hoursSpent });

6.​ 📥 Doctor-Hospital Structure — Track hoursSpent in both doctor & hospital


models using nested objects.​

Prettier in Short
✅ What?
👉 A tool to auto-format your code (clean, consistent style)
🛠️ Install:
bash

CopyEdit

npm i -D prettier

⚙️ Create .prettierrc
json

CopyEdit

"semi": true,

"singleQuote": true,

"tabWidth": 2

🙅‍♂️ Ignore Files with .prettierignore


bash

CopyEdit

node_modules/

build/

.env
🚀 Run Prettier
bash

CopyEdit

npx prettier --write .

💻 VS Code
●​ Install Prettier extension​

●​ Enable Format On Save​

🧠 TL;DR
Tool Purpose

Prettier Auto-format code

.prettierrc Set formatting


rules

.prettierignor Skip files


e
Data base
While data connect 2 things remember
1. Always try catch apply or promise ( then and catch)
2. Apply asynchronous becoz something data fetching took to much time becoz its a
third part or your data store some where network issue or something like that

What is mongoose-aggregate-paginate-v2?
It’s a Mongoose plugin used to add pagination support to MongoDB aggregate queries.

🔁 Why use it?


Normally:

●​ Pagination is easy with .find().limit().skip()​

●​ But for complex data, we use aggregate()​

👉 Aggregation doesn't support simple .skip() and .limit() with meta info like total
docs, total pages etc.

✅ This plugin makes that easy and clean.

⚙️ How it works?
It wraps around your .aggregate() query and adds:

●​ limit, skip​

●​ totalDocs, totalPages, page, pagingCounter​

Basically, it gives you a paginated response based on your aggregation pipeline.

bcrypt in Backend (Authentication):

bcrypt is a password hashing library used to securely store user passwords in


databases.
🔧 Why use bcrypt?
●​ Plaintext passwords are insecure if your database is hacked.​

●​ Hashing converts passwords into unreadable strings.​

●​ bcrypt adds salt (random data) to make the hash unique even if two users have
the same password.​

●​ It's slow by design, making brute-force attacks difficult.

What is JWT?

JWT is a compact, URL-safe token used to verify users across requests once they log in.

It contains 3 parts:

css
CopyEdit
header.payload.signature

Example:

js
CopyEdit
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.
eyJ1c2VySWQiOiIxMjM0NTY3ODkwIiwiaWF0IjoxNjg5ODc2MDB9.
dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk

🧠 Why use JWT?


●​ Stateless: No need to store session on the server.​

●​ Secure (if secret is strong and used properly).​

●​ Easy to send in headers (Authorization: Bearer <token>).​

✅ How JWT works:


1.​ User logs in → Server verifies → creates token using jwt.sign().​

2.​ Token sent to frontend.​

3.​ Frontend stores it (usually in localStorage or cookies).​

4.​ On every request, frontend sends token in headers.​

5.​ Backend verifies it using jwt.verify().

🔄 Access Token & Refresh Token — Complete Concept


✅ What is an Access Token?
●​ A short-lived token (e.g., 15–60 mins).​

●​ Used to authenticate requests to protected routes.​

●​ Sent in headers as:​


Authorization: Bearer <access_token>​

♻️ What is a Refresh Token?


●​ A long-lived token (e.g., 7–30 days).​

●​ Used to generate new access tokens when they expire.​

●​ Usually stored in a secure place like HTTP-only cookies.​

🧠 Why Use Both?


Access Token Refresh Token

Short lifespan Long lifespan

Used frequently Used only on expiration

Safer even if More sensitive


leaked
Authenticates Regenerates Access
APIs Token

HTTP (HyperText Transfer Protocol)

●​ URL format: http://​

●​ Security: ❌ Not encrypted (data sent in plain text)​


●​ Port: Uses port 80​

●​ Use Case: Testing/local dev (rarely), older websites​

●​ Speed: Slightly faster (no encryption overhead)​

●​ Trust: ❌ Not trusted by browsers for sensitive info​

🔹 HTTPS (HyperText Transfer Protocol Secure)


●​ URL format: https://​

●​ Security: ✅ Encrypted using SSL/TLS​


●​ Port: Uses port 443​

●​ Use Case: ✅ Industry standard for all modern websites, especially those handling data
(banking, login, e-commerce, etc.)​

●​ Speed: Slightly slower, but optimized with modern tech​

●​ Trust: ✅ Trusted by browsers, improves SEO​


User agent means postman or some website say use our website that type

You might also like