0% found this document useful (0 votes)
31 views23 pages

Details of Express Js

Express.js is a lightweight Node.js framework for building APIs and web applications, simplifying HTTP usage with features like routing and middleware. It allows for easy handling of JSON, form data, and REST APIs, making it a popular choice among developers. Key concepts include routing, middleware functions, request/response handling, and error management.

Uploaded by

xeroxxwala
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)
31 views23 pages

Details of Express Js

Express.js is a lightweight Node.js framework for building APIs and web applications, simplifying HTTP usage with features like routing and middleware. It allows for easy handling of JSON, form data, and REST APIs, making it a popular choice among developers. Key concepts include routing, middleware functions, request/response handling, and error management.

Uploaded by

xeroxxwala
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/ 23

EXPRESS.

JS
IN DETAILS
IMPORTANTS
node vs express, what is the real deal ?
what is express js ?
why express js ?
localhost, hostname, port number
Routing
Middleware
Request and Response
Route Parameters
HTTP Methods - get and post
Error Handling
Postman
NODE VS EXPRESS, WHAT IS THE REAL DEAL ?

Node is the main thing through which we can write the server code and how
server will react that also we can do using the help of express .

WHAT IS EXPRESS JS

Express is a Node js framework designed for building APIs, web applications


and cross-platform mobile apps.

Express is high performance, fast, unopinionated , and lightweight.

It is used as a server-side scripting language.


WHY EXPRESS JS

HTTP is difficult to use, express makes this easier

✅ Easy Routing
✅ Large Community
Reasons to use:
✅ Handles JSON & Forms
✅ Works with Templates
✅ REST API Ready
✅ Middleware Support
1. Hostname
The hostname is the name of a computer or server on a network
Example:
"www.example.com" is a hostname.
"localhost" is a special hostname referring to your own computer.

2. Localhost
localhost is a reserved hostname that points to the local computer.
It is commonly used for testing and development.
Example:
When you run a backend server on your own PC, it can be accessed via
http://localhost:3000 (3000 is a port).

3. Port
A port is a number (from 0 to 65535) used to identify a specific process
or service on a machine.
Example:
http://localhost:3000 → Port 3000 is used by your backend server.
Where to use which PORT Number ?

Port Number Common Use

React.js frontend or
3000 Express.js backend

5000 Backend APIs or Node


servers

8000 Django, Flask, or other


servers

Alternate HTTP for


8080 testing
🔁 Why Use Nodemon?
Nodemon is a developer tool for Node.js that automatically restarts your server
whenever you make changes to your code files.

Problem Without Nodemon:

When you're using plain Node.js, every time you make a change in your server
file (like server.js), you have to:

ctrl + c to stop the server


node server.js to start the server
1. Install it globally:

npm install -g nodemon

or locally as a dev dependency:

npm install --save-dev nodemon

2. Run your app with nodemon:

nodemon server.js
ROUTING
Routing is the process of defining how your server responds to different URL paths
(routes) that a client (like a browser) requests.

Examples:
/profile
/home
/contact
/profile/profile_details/jhsaasdggdsds/okoksdhashabchbd
//✅ PUT Method Example
// Import express app.put('/user/:id', (req, res) => {
const express = require('express'); const userId = req.params.id;
const app = express(); const updatedData = req.body;
✏️
console.log(` Updating user with ID ${userId}:`, updatedData);
// Middleware to handle JSON data 🔄
res.send(` User with ID ${userId} updated with data:
app.use(express.json()); ${JSON.stringify(updatedData)}`);
});
//✅ GET Method Example
//✅ DELETE Method Example
app.get('/welcome', (req, res) => {
👋
res.send(' Hello! This is a GET request.');
app.delete('/user/:id', (req, res) => {
const userId = req.params.id;
});
🗑️
console.log(` Deleting user with ID ${userId}`);

//✅ POST Method Example



res.send(` User with ID ${userId} has been deleted.`);
});
app.post('/user', (req, res) => {
const userData = req.body; // Start the server
📦
console.log(' Data received from client (POST):', userData); const PORT = 5000;

res.send(` User data received: ${JSON.stringify(userData)}`); app.listen(PORT, () => {
}); 🚀
console.log(` Server running at http://localhost:${PORT}`);
});
Without using Express Routing

const http = require('http');

const server = http.createServer((req, res) => {


if (req.url === '/') {
res.writeHead(200, { 'Content-Type': 'text/plain' });
👋
res.end(' Hello! You are on the homepage.');
} else if (req.url === '/about') {
res.writeHead(200, { 'Content-Type': 'text/plain' });
📘
res.end(' This is the About page.');
} else {
res.writeHead(404, { 'Content-Type': 'text/plain' });

res.end(' 404 Not Found');
}
});

const PORT = 5000;


server.listen(PORT, () => {
🚀
console.log(` Server running at http://localhost:${PORT}`);
});
WHAT IS MIDDLEWARE ?

Middleware functions are functions that have access to the request object(req),
the response object(res), and the next middleware function in the applications
request-response cycle.
(req, res, next) => { ... }

req: Incoming request object


res: Outgoing response object
next: Function that passes control to the next middleware

Types of Middleware:

1. ✅ Built-in Middleware
app.use(express.json()); // parses incoming JSON requests

2. ✅ Application-level Middleware
app.use((req, res, next) => {
📥
console.log(` Request to ${req.url}`);
next();
});
3. ✅ Router-level Middleware
const router = express.Router();

router.use((req, res, next) => {


🔗
console.log(' Router-level middleware');
next();
});

4. ✅ Error-handling Middleware
app.use((err, req, res, next) => {

console.error(' Error:', err.message);
res.status(500).send('Something broke!');
});
5. ✅ Third-party Middleware
const cors = require('cors');
app.use(cors()); // allow cross-origin requests
Example: const express = require('express');
const app = express();

//✅ Custom Middleware


const logger = (req, res, next) => {
console.log(`${req.method} ${req.url}`);
next(); // continue to the next middleware or route
};

app.use(logger); // apply middleware to all routes

app.get('/', (req, res) => {


🏠
res.send(' Home Page');
});

app.get('/about', (req, res) => {


ℹ️
res.send(' About Page');
});

app.listen(5000, () => {
console.log('Server running on http://localhost:5000');
});
📩 Request (req)
A request is sent from the client to the server when the user:
Visits a webpage
Submits a form
Sends an API call
Request object contains
📤 Response (res)
A response is what the server sends back to the client.

🔹 Response object allows:


🔑 What Are Route Parameters?
Route Parameters are variables in your route URL that capture dynamic values from
the client.
Example:

http://localhost:5000/user/123
const express = require('express');
const app = express();

app.get('/user/:id', (req, res) => {


const userId = req.params.id; // Access route parameter
👤
res.send(` User ID is: ${userId}`);
});

app.listen(5000, () => {
🚀
console.log(' Server is running on http://localhost:5000');
});

Click here:👉 Express routing


Multiple Parameters are also possible:

app.get('/user/:userId/post/:postId', (req, res) => {


const { userId, postId } = req.params;
res.send(`User ID: ${userId}, Post ID: ${postId}`);
});
Error handling
Error handling is essential in any web application to gracefully deal with unexpected situations like:
Database connection failures
Invalid inputs
Missing routes
Server crashes
const express = require('express');
const app = express();

app.use(express.json());

// Example route that throws an error


app.get('/error', (req, res) => {
🚨
throw new Error(' Something went wrong!');
});

//✅ Error Handling Middleware (should be after routes)


app.use((err, req, res, next) => {

console.error(' Error caught by middleware:', err.message);

res.status(500).json({
success: false,
message: err.message || 'Internal Server Error',
});
});

// Start server
app.listen(5000, () => {
🚀
console.log(' Server is running on http://localhost:5000');
});
Postman

You might also like