Express Js
Express Js
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
NPM stands for Node Package Manager, responsible for managing all the packages and
modules for Node.js.
Modules are individual units of reusable code that can be included in a Node.js
application.
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?
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.
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.
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.
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.
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.
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.
● 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.
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] )
resource.
● PUT: The PUT method is used to update a resource or create a new resource if it
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,
● next: This is a callback function that is used to pass control to the next middleware
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.
IMPLEMENTATIONAL QUESTIONS
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.
app.use(bodyParser.json());
2.What is a mongoose?
Mongoose is the ODM library which is used to establish the connection between the
ExpressJs and MongoDB databases.
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”
}
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
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>`);
});
try {
`${process.env.REACT_APP_BASE_URL}/getTodos`,
method: "GET",
headers: {
"Content-Type": "application/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
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
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.
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);
}
// 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!",
};
__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.
1. Pre Middleware
Pre middleware functions are executed before the specified action takes place.
Example:
const mongoose = require('mongoose');
// Pre-save middleware
userSchema.pre('save', function(next) {
}
next();
});
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');
userSchema.post('save', function(doc) {
console.log(`User ${doc.name} has been saved.`);
});
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.