0% found this document useful (0 votes)
17 views17 pages

Express Js

The document provides a comprehensive overview of Node.js and Express.js, detailing their functionalities, features, and key components. It covers topics such as asynchronous processing, middleware, routing, and the use of various libraries and tools like NPM, Mongoose, and Bcrypt. Additionally, it explains the structure of an Express application, error handling, and integration with frontend frameworks.

Uploaded by

jaykumarguptajti
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)
17 views17 pages

Express Js

The document provides a comprehensive overview of Node.js and Express.js, detailing their functionalities, features, and key components. It covers topics such as asynchronous processing, middleware, routing, and the use of various libraries and tools like NPM, Mongoose, and Bcrypt. Additionally, it explains the structure of an Express application, error handling, and integration with frontend frameworks.

Uploaded by

jaykumarguptajti
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
You are on page 1/ 17

BACKEND

Node Js

1. What is Node.js? Where can you use it?


NodeJs is the javascript runtime environment that allows JS code to execute outside the
browser. It is used for server-side programming.

2. Why use Node.js?

Node.js makes building scalable network programs easy. Some of its advantages include:

●​ It is generally fast
●​ Familiar to JS
●​ Everything is asynchronous

3. How does Node.js work?

4. Why is Node.js Single-threaded?

Node.js is single-threaded for async processing. By doing async processing on a


single-thread under typical web loads, more performance and scalability can be achieved
instead of the typical thread-based implementation.
5. If Node.js is single-threaded, then how does it handle concurrency?

The Multi-Threaded Request/Response Stateless Model is not followed by the Node JS


Platform, and it adheres to the Single-Threaded Event Loop Model.

6. Explain callback in Node.js.

A callback function is called after a given task.

7. What are the advantages of using promises instead of callbacks?

●​ The control flow of asynchronous logic is more specified and structured.


●​ We've built-in error handling.
●​ Improved readability.

11. What is NPM?

NPM stands for Node Package Manager, responsible for managing all the packages and
modules for Node.js.

12. What are the modules in Node.js?

Modules are individual units of reusable code that can be included in a Node.js
application.

13. What is the purpose of the module .Exports?

In Node.js, a module encapsulates all related codes into a single unit of code which lets it
be imported into another file with a needed keyword.

17. What are some of the most commonly used libraries in Node.js?

●​ ExpressJS - Express is a lightweight Node.js framework that provides a wide set of


features to develop web and mobile applications.
●​ Mongoose - Mongoose is also a Node.js web application framework that makes it easy
to connect an application to a database.
EXPRESS JS

1.​ What is Express Js?


Express.js is a lightweight framework that works on top of Node.js. It makes easier to
organize your application’s functionality with middleware and routing. Express is the
part of MERN stack.

2.​ Important Features?


Middleware, Routing, API Handling, Simplified, Third-Party Middleware, Scalability.

3.​ Installation and first program


npm install express

4. Differentiate between Node.js and Express.js?

Node.js is the runtime environment that allows you to execute JavaScript on the server side,
on the other hand Express.js is a framework built on top of Node.js that provides a set of
tools for building web applications and APIs.

5. Middleware and Routing?

Middleware is a function that runs during the request-response cycle in an Express.js


application. It processes requests, performs tasks, and then either ends the response or
forwards the request to the next middleware. For eg: Logging, authentication, etc.
Routing refers to defining endpoints (URIs) in the application and specifying what to do
when users visit them. Routing is based on the HTTP method (GET, POST, PUT, DELETE, etc.) and the URL
path.
9. Which major tools can be integrated with Express JS?

●​ Database tools: MongoDB, MySQL, PostgreSQL.

●​ Template Engines: EJS, Pug, Mustache.

●​ Authentication libraries: Passport.js, bcypt..

●​ Validation libraries: Jwt

●​ ORM libraries: Mongoose

10. What is .env file used for?

The .env file is used for storing sensitive information in a web application which we don't
want to expose to others like password, database connection string etc. It is a simple text
file where each line represents a key-value pair, and these pairs are used to configure
various aspects of the application.

11. What are JWT?

Json Web Tokens are mainly a token which is used for authentication and information
exchange. When a user signs in to an application, the application then assigns JWT to that
user. Subsequent requests by the user will include the assigned JWT. This token tells the
server what routes, services, and resources the user is allowed to access.
Json Web Token includes 3 part namely- Header, Payload and Signature.

12. What is Bcrypt used for?

Bcrypt is a password hashing function which is used to securely hash and store user
passwords. It is designed to be slow and computationally intensive, making it resistant to
brute-force attacks and rainbow table attacks. Bcrypt is a key component in enhancing the
security of user authentication systems.

15. What do you understand about ESLint?

EsLint is a JavaScript linting tool which is used for automatically detecting incorrect patterns
found in ECMAScript/JavaScript code. It is used with the purpose of improving code quality,
making code more consistent, and avoiding bugs. ESLint is written using Node.js to provide a
fast runtime environment and easy installation via npm.
17. Differentiate between res.send() and res.json().

Both res.send() and res.json() serves similar purposes with some difference. So it depends
on the data type which we are working with. Choose res.json() when you are specifically
working with JSON data. Use res.send() {Sends a response of any type (string, buffer, object, etc} when
you need versatility and control over the content type or when dealing with various data
types in your responses.

18. What is meant by Scaffolding in Express JS?

Scaffolding in Express.js refers to the process of generating a basic project structure


automatically. This can speed up the initial setup and help maintain consistency in the way
projects are structured, especially in large teams.

21. Explain what CORS is in Express JS?

CORS (Cross-Origin Resource Sharing) is a security feature implemented by web browsers


to control how web pages in one domain can request and interact with resources hosted on
another domain.
In the context of Express.js, CORS refers to a middleware that enables Cross-Origin
Resource Sharing for your application. This allows the application to control which domains
can access your resources by setting HTTP headers.

22. What are Built-in Middlewares?

Express.js, includes a set of built-in middlewares that provide common functionality.


These built-in middlewares are included by default when you create an Express
application and can be used to handle various tasks. Here are some of the built-in
middlewares in Express:
●​ express.json(): This middleware is used to parse incoming JSON requests. It
automatically parses the request body if the Content-Type header is set to
application/json.
●​ express.Router(): The express.Router() function is often used to create
modular route handlers. It allows you to group route handlers together and
then use them as a middleware.

24. Which template engines do Express support?

Express.js supports any template engine that follows the (path, locals, callback) signature.
28. What is the use of 'Response.cookie()' function?

The response.cookie() function in Express.js is used to set cookies in the HTTP response.
Cookies are small pieces of data sent from a server and stored on the client's browser. They
are commonly used to store information about the user or to maintain session data.
Basic syntax of response.cookie():
res.cookie(name, value, [options]);

29. Under what circumstances does a Cross-Origin resource fail in Express JS?

When a Cross-Origin Resource Sharing request is made, the browser enforces certain
security checks, and the request may fail under various circumstances:
●​ No CORS Headers: The server doesn't include the necessary CORS headers in its

response.

●​ Mismatched Origin: The requesting origin does not match the origin specified in the

Access-Control-Allow-Origin header.

●​ Restricted HTTP Methods: The browser enforces restrictions on which HTTP

methods are allowed in cross-origin requests.

●​ No Credentials: The browser makes restrictions on requests that include

credentials (such as cookies or HTTP authentication).

34. What are the types of middlewares?

There are mainly five types of Middleware in Express.js:


●​ Application-level middleware

●​ Router-level middleware

●​ Error-handling middleware

●​ Built-in middleware

●​ Third-party middleware
37. When application-level Middleware is used?

Application-level middlewares are bound to an instance of the Express application and are
executed for every incoming request. These middlewares are defined using the app.use()
method, and they can perform tasks such as logging, authentication, setting global
variables, and more.

38. Explain Router-level Middleware.

Router-level middlewares are specific to a particular router instance. This type of


middleware is bound to an instance of express.Router(). Router-level middleware works
similarly to application-level middleware, but it's only invoked for the routes that are
handled by that router instance. This allows you to apply middleware to specific subsets of
your routes, keeping your application organized and manageable.

40. What is Express router() function?

The express.Router() function is used to create a new router object. This function is used
when you want to create a new router object in your program to handle requests.
Syntax:
express.Router( [options] )

41. What are the different types of HTTP requests?


The primary HTTP methods are commonly referred to as CRUD operations, representing
Create, Read, Update, and Delete. Here are the main HTTP methods:
●​ GET: The GET method is used to request data from a specified resource.

●​ POST: The POST method is used to submit data to be processed to a specified

resource.

●​ PUT: The PUT method is used to update a resource or create a new resource if it

does not exist.

●​ PATCH: The PATCH method is used to apply partial modifications to a resource.

●​ DELETE: The DELETE method is used to request that a specified resource be

removed.
43. Which are the arguments available to an Express JS route handler function?
●​ req: This represents the HTTP request object which holds information about the

incoming request. It allows you to access and manipulate the request data.

●​ res: This represents the HTTP response object which is used to send the response

back to the client. It provides methods and properties to set response headers,

status codes, and send the response body.

●​ next: This is a callback function that is used to pass control to the next middleware

function in the request-response cycle.

44. How can you deal with error handling in Express.js?

Middleware, next() function, try catch()

45. What is the difference between a traditional server and an Express.js


server?
A traditional server is a server that is built and managed independently. Traditional server
may provide a basic foundation for handling HTTP requests and responses. While an
Express.js server is built using the Express.js framework. It runs on top of Node.js. Express.js
provides a simple and efficient way to create and manage web applications. It offers a wide
range of features and tools for handling routing, middleware, and request or response
objects.

46. What is the purpose of the next() function in Express.js?

The next() function is used to pass control from one middleware function to the next
function. It is used to execute the next middleware function in the chain. If there are no next
middleware function in the chain then it will give control to router or other functions in the
app.

If you don't call next() in a middleware function, the request-response cycle can be
terminated, and subsequent middleware functions won't be executed.
47. What is the difference between app.route() and app.use() in Express.js?

app.route() is more specific to route handling and allows you to define a sequence of
handlers for a particular route, on the other hand app.use() is a more general-purpose
method for applying middleware globally or to specific routes.

50. What is the use of app.use() in Express.js?

app.use() is used to add/mount the middleware functions in an Express application. It can be


used to add global middleware functions or to add middleware functions to specific routes.

IMPLEMENTATIONAL QUESTIONS

1.​What is a body Parser?

Body Parser is the middleware that parse the incoming HTTP request and make the data
accessible. It converts JSON or Form data into JS Object.

Const bodyParser = require(‘body-parser’);

app.use(bodyParser.json());

// connection btw mongoDB and ExpressjS

2.​What is a mongoose?

Mongoose is the ODM library which is used to establish the connection between the
ExpressJs and MongoDB databases.

const mongoose = require('mongoose');


Const dbConnect = () => {
mongoose.connect('mongodb://localhost:27017/mydb',{
useNewUrlParser: true,
useUnifiedTopology: true
}).then(()=>{console.log("Database Connected Successful")})
.catch(()=>{console.log("Failed to connected")})
}
module.exports = dbConnect;
3.​What is Nodemon?

Nodemon is the package used to update and restart the server automatically when there are
some changes.
Start script: {
"start": "node index.js"
“dev” : ”nodemon index.js”
}

4.​Folder Structure in ExpressJs?

We follow MVC pattern


index.js -> routes -> controllers -> models, config (dbconnect, cloudinary, etc)

Step 1:- config -> write dbconnect function using mongoose.connect()


Step 2:- Creating Schemas(Models) ->
const mongoose = require("mongoose");
const todoSchema = new mongoose.Schema(
{
title : {
type:String,
required:true,
maxLength:20
},
description:{
type:String,
required:true,
maxLength:50
}
}
);
module.exports = mongoose.model("Todo",todoSchema);
Step 3:- Writing Controllers:-
They are application specific generally CRUD.
1.​CREATE :
const Todo = require("../models/Todo");
exports.createTodo = async(req, res) => {
try
{
​ // extract details, validate, store in db, and return response
const {name, desc} = req?.body;
​ if(!name || !desc) return res.status(401).json(message:””);
const todo = await Todo.create({name, desc}); // obj.save()
return res.status(200).json({
​ Success: true,
​ Data: todo,
​ Message: “Data Saved”
})
}catch(err)
{
console.log(err);
res.status(500).json({
success:false,
data:"Internal server issue",
message:err.message,
})
}
}

2.​GET:
a.​const all = await Todo.find({});
b.​const res = await Todo.findById({_id: id});
c.​const user = await Todo.findOne({name: username, age: 20});
3.​DELETE:
a.​await Todo.findByIdAndDelete({_id: id});
b.​await Todo.findByIdAndDelete({name: name});
c.​await Todo.findByIdAndDelete({});
4.​UPDATE:
a.​const updated = await Todo.findByIdAndUpdate({_id: id},{ $push: {title,
desc,..}},{new:true});
b.​const updatedUser = await User.findByIdAndUpdate(
c.​ userId, // ID of the document
d.​ { $set: { age: 30 } }, // Update query
e.​ { new: true } // Options
f.​ );
Step 3:- Routes:-
const express = require(‘express’);
const router - express.Router();
router.get(“/getTodo”,contoller);
module.exports = router

Step 3:- index.js :-


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

require("dotenv").config();
const PORT = process.env.PORT || 5000;

// middleware
app.use(express.json()); // for parsing

// import routes
const todoRouter = require("./routes/todos");
// mount API routes
app.use("/api/v1",todoRouter);

app.listen(3300,()=>{
console.log(`Server is started at port 3300`);
})

// connect to DB
const dbConnect = require("./config/database");
dbConnect();

// default route
app.get("/",(req,res)=>{
res.send(`<h1>This is HOME </h1>`);
});

The V8 engine is an open-source JavaScript and WebAssembly engine developed by


Google. It is written in C++ and is used to execute JavaScript code.
5.​ How to Refer the Object of some other Schema

like :[{ type: mongoose.Schema.Types.ObjectId, ref: 'blogLike' }],

6.​ Integration of Backend with Frontend?


Backend same code + app.use(cors({origin: “ “}));
Frontend:-
REACT_APP_BASE_URL = "http://localhost:5500/api/v1" (server is running at 5500)

const [todos,setTodos] = useState();

const getAllTodos = async()=>{

try {

const getTodos = await fetch(

`${process.env.REACT_APP_BASE_URL}/getTodos`,

method: "GET",

headers: {

"Content-Type": "application/json",

},

);

const res = await getTodos.json();

setTodos(res);

} catch (error) {

console.log("error");

useEffect(()=>{

getAllTodos();

},[])
Authentication & Authorization

​ JWT Login:
token = jwt.sign(payload, secret, options);
​ res.cookies(name, value. options);
​ res.cookies(“jwt”, token, {});

​ Auth middleware:
​ Fetch the token
Headers(Bearer token), body, cookie-parser
decode = jwt.verify(token, secret);
req.user = decode

isStudent, isAdmin, isInstructor


if(req.user.role! = “Student”) return false;

LOGIN & SINGUP LOGIC

Singup:
1.​ Fetch details of user
2.​ Validate them
3.​ Check for existence of user; if already found return
4.​ Hash the password; hashedPassword = bcrypt.hash(password, 10)
5.​ Store user in the DB

Login:
6.​ Fetch details of user email & password
7.​ Validate them
8.​ Check for existence of user; if not found return (existenceUser)
9.​ result = brcypt.compare(password, bdPassword)
10.​ if(result):
a.​ Create JWT
b.​ Send in cookies
FILE UPLOAD

Cloudinary Integration :- is the third-party cloud storage for managing multimedia.

1.​ Create Account on cloudinary get API keys and secret Keys
2.​ npm install cloudinary
3.​ Configure Coludinary:- cloudinary.config()
4.​ Use cloudinary.uploader.upload() to store the data on cloud and get secureUrl.

const cloudinary = require("cloudinary").v2;


require("dotenv").config();

exports.cloudinaryConnect = () =>{

try{
cloudinary.config({
cloud_name:process.env.CLOUD_NAME,
api_key:process.env.API_KEY,
api_secret: process.env.API_SECRET,
})

}catch(err)
{
console.log(err);
}

Nodemailer Integration:- it is the library used to send emails easily.

1.​ Create Transport


2.​ Transport.sendMail(mailOptions, callback)

const nodemailer = require("nodemailer");

// Create a transporter
const transporter = nodemailer.createTransport({
service: "gmail",
auth: {
user: "[email protected]",
pass: "your-email-password", // Use App Password for Gmail
},
});
// Email options
const mailOptions = {
from: "[email protected]",
to: "[email protected]",
subject: "Test Email",
text: "Hello, this is a test email sent using Nodemailer!",
};

// Send the email


transporter.sendMail(mailOptions, (error, info) => {
if (error) {
console.log("Error:", error);
} else {
console.log("Email sent:", info.response);
}
});

__dirname is a global variable in Node.js that represents the absolute path of the directory
where the currently executing JavaScript file is located.

A webhook is a way for web applications to communicate with each other in real time. It allows one application
to send automated HTTP requests (usually POST) to another application when a specific event occurs.

PRE POST MIDDLEWARE


In Mongoose, pre and post middleware (also called hooks) are functions that are executed before or after certain
actions (such as saving, updating, or deleting) are performed on a document or model.

1. Pre Middleware
Pre middleware functions are executed before the specified action takes place.

Example:
const mongoose = require('mongoose');

const userSchema = new mongoose.Schema({


name: String,
email: String,
});

// Pre-save middleware
userSchema.pre('save', function(next) {
}
next();
});

const User = mongoose.model('User', userSchema);

2. Post Middleware
Post middleware functions are executed after the specified action is completed successfully. You can use them to
perform tasks after the action, such as, sending notifications or sending Mails.

Example:
const mongoose = require('mongoose');

const userSchema = new mongoose.Schema({


name: String,
email: String,
});

userSchema.post('save', function(doc) {
console.log(`User ${doc.name} has been saved.`);
});

Types of Operations You Can Attach Middleware To:


●​ save: Before or after saving a document (pre('save'), post('save')).
●​ validate: Before or after validation (pre('validate'), post('validate')).
●​ remove: Before or after removing a document (pre('remove'), post('remove')).
●​ update/updateOne/updateMany: Before or after updating documents (pre('update'), post('update')).
●​ findOneAndUpdate: Before or after findOneAndUpdate operation (pre('findOneAndUpdate'),
post('findOneAndUpdate')).

Key Notes:
●​ Pre middleware must call next() to proceed with the operation.
●​ Post middleware doesn't need to call next() since it runs after the operation.
●​ You can also access the document or result in both pre and post middleware, depending on the operation.

You might also like