BACKEND
Node Js
1. What is [Link]? 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 [Link]?
[Link] makes building scalable network programs easy. Some of its advantages include:
● It is generally fast
● Familiar to JS
● Everything is asynchronous
3. How does [Link] work?
4. Why is [Link] Single-threaded?
[Link] 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 [Link] 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 [Link].
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 [Link].
12. What are the modules in [Link]?
Modules are individual units of reusable code that can be included in a [Link]
application.
13. What is the purpose of the module .Exports?
In [Link], 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 [Link]?
● ExpressJS - Express is a lightweight [Link] framework that provides a wide set of
features to develop web and mobile applications.
● Mongoose - Mongoose is also a [Link] web application framework that makes it easy
to connect an application to a database.
EXPRESS JS
1. What is Express Js?
[Link] is a lightweight framework that works on top of [Link]. 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 [Link] and [Link]?
[Link] is the runtime environment that allows you to execute JavaScript on the server side,
on the other hand [Link] is a framework built on top of [Link] 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 [Link]
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: [Link], 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 [Link] to provide a
fast runtime environment and easy installation via npm.
17. Differentiate between [Link]() and [Link]().
Both [Link]() and [Link]() serves similar purposes with some difference. So it depends
on the data type which we are working with. Choose [Link]() when you are specifically
working with JSON data. Use [Link]() {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 [Link] 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 [Link], 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?
[Link], 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:
● [Link](): 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.
● [Link](): The [Link]() 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?
[Link] supports any template engine that follows the (path, locals, callback) signature.
28. What is the use of '[Link]()' function?
The [Link]() function in [Link] 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 [Link]():
[Link](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 [Link]:
● 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 [Link]()
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 [Link](). 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 [Link]() 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:
[Link]( [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 [Link]?
Middleware, next() function, try catch()
45. What is the difference between a traditional server and an [Link]
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
[Link] server is built using the [Link] framework. It runs on top of [Link]. [Link]
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 [Link]?
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 [Link]() and [Link]() in [Link]?
[Link]() is more specific to route handling and allows you to define a sequence of
handlers for a particular route, on the other hand [Link]() is a more general-purpose
method for applying middleware globally or to specific routes.
50. What is the use of [Link]() in [Link]?
[Link]() 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’);
[Link]([Link]());
// 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 = () => {
[Link]('mongodb://localhost:27017/mydb',{
useNewUrlParser: true,
useUnifiedTopology: true
}).then(()=>{[Link]("Database Connected Successful")})
.catch(()=>{[Link]("Failed to connected")})
}
[Link] = 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 [Link]"
“dev” : ”nodemon [Link]”
}
4.Folder Structure in ExpressJs?
We follow MVC pattern
[Link] -> routes -> controllers -> models, config (dbconnect, cloudinary, etc)
Step 1:- config -> write dbconnect function using [Link]()
Step 2:- Creating Schemas(Models) ->
const mongoose = require("mongoose");
const todoSchema = new [Link](
{
title : {
type:String,
required:true,
maxLength:20
},
description:{
type:String,
required:true,
maxLength:50
}
}
);
[Link] = [Link]("Todo",todoSchema);
Step 3:- Writing Controllers:-
They are application specific generally CRUD.
1.CREATE :
const Todo = require("../models/Todo");
[Link] = async(req, res) => {
try
{
// extract details, validate, store in db, and return response
const {name, desc} = req?.body;
if(!name || !desc) return [Link](401).json(message:””);
const todo = await [Link]({name, desc}); // [Link]()
return [Link](200).json({
Success: true,
Data: todo,
Message: “Data Saved”
})
}catch(err)
{
[Link](err);
[Link](500).json({
success:false,
data:"Internal server issue",
message:[Link],
})
}
}
2.GET:
a.const all = await [Link]({});
b.const res = await [Link]({_id: id});
c.const user = await [Link]({name: username, age: 20});
3.DELETE:
a.await [Link]({_id: id});
b.await [Link]({name: name});
c.await [Link]({});
4.UPDATE:
a.const updated = await [Link]({_id: id},{ $push: {title,
desc,..}},{new:true});
b.const updatedUser = await [Link](
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 - [Link]();
[Link](“/getTodo”,contoller);
[Link] = router
Step 3:- [Link] :-
const express = require("express");
const app = express();
require("dotenv").config();
const PORT = [Link] || 5000;
// middleware
[Link]([Link]()); // for parsing
// import routes
const todoRouter = require("./routes/todos");
// mount API routes
[Link]("/api/v1",todoRouter);
[Link](3300,()=>{
[Link](`Server is started at port 3300`);
})
// connect to DB
const dbConnect = require("./config/database");
dbConnect();
// default route
[Link]("/",(req,res)=>{
[Link](`<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: [Link], ref: 'blogLike' }],
6. Integration of Backend with Frontend?
Backend same code + [Link](cors({origin: “ “}));
Frontend:-
REACT_APP_BASE_URL = "[Link] (server is running at 5500)
const [todos,setTodos] = useState();
const getAllTodos = async()=>{
try {
const getTodos = await fetch(
`${[Link].REACT_APP_BASE_URL}/getTodos`,
method: "GET",
headers: {
"Content-Type": "application/json",
},
);
const res = await [Link]();
setTodos(res);
} catch (error) {
[Link]("error");
useEffect(()=>{
getAllTodos();
},[])
Authentication & Authorization
JWT Login:
token = [Link](payload, secret, options);
[Link](name, value. options);
[Link](“jwt”, token, {});
Auth middleware:
Fetch the token
Headers(Bearer token), body, cookie-parser
decode = [Link](token, secret);
[Link] = decode
isStudent, isAdmin, isInstructor
if([Link]! = “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 = [Link](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 = [Link](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:- [Link]()
4. Use [Link]() to store the data on cloud and get secureUrl.
const cloudinary = require("cloudinary").v2;
require("dotenv").config();
[Link] = () =>{
try{
[Link]({
cloud_name:[Link].CLOUD_NAME,
api_key:[Link].API_KEY,
api_secret: [Link].API_SECRET,
})
}catch(err)
{
[Link](err);
}
Nodemailer Integration:- it is the library used to send emails easily.
1. Create Transport
2. [Link](mailOptions, callback)
const nodemailer = require("nodemailer");
// Create a transporter
const transporter = [Link]({
service: "gmail",
auth: {
user: "your-email@[Link]",
pass: "your-email-password", // Use App Password for Gmail
},
});
// Email options
const mailOptions = {
from: "your-email@[Link]",
to: "recipient@[Link]",
subject: "Test Email",
text: "Hello, this is a test email sent using Nodemailer!",
};
// Send the email
[Link](mailOptions, (error, info) => {
if (error) {
[Link]("Error:", error);
} else {
[Link]("Email sent:", [Link]);
}
});
__dirname is a global variable in [Link] 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 [Link]({
name: String,
email: String,
});
// Pre-save middleware
[Link]('save', function(next) {
}
next();
});
const User = [Link]('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 [Link]({
name: String,
email: String,
});
[Link]('save', function(doc) {
[Link](`User ${[Link]} 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.