0% found this document useful (0 votes)
21 views53 pages

Question 2

The document compares client-side and server-side applications in web development, highlighting their definitions, execution environments, technologies, responsibilities, performance, security, scalability, and when to use each. It also explains how to set up and use Node.js with NPM for managing dependencies in a web project, as well as serving files using the http module in Node.js. Additionally, it discusses the Express framework, emphasizing how it simplifies web server development by providing routing, middleware, and static file serving functionalities.

Uploaded by

Hetal Mer
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as ODT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views53 pages

Question 2

The document compares client-side and server-side applications in web development, highlighting their definitions, execution environments, technologies, responsibilities, performance, security, scalability, and when to use each. It also explains how to set up and use Node.js with NPM for managing dependencies in a web project, as well as serving files using the http module in Node.js. Additionally, it discusses the Express framework, emphasizing how it simplifies web server development by providing routing, middleware, and static file serving functionalities.

Uploaded by

Hetal Mer
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as ODT, PDF, TXT or read online on Scribd
You are on page 1/ 53

Compare the client-side and server-side applications.

Web development typically involves two primary areas of functionality: client-side and server-
side. Both are essential in delivering dynamic, interactive, and efficient applications, but they
operate in different environments and serve different purposes. Understanding the distinction
between them is crucial for developers, as it directly impacts performance, security, and user
experience.

1. Definitions
Client-side Application
A client-side application is one where most of the code is executed on the user's device (i.e., the
client). This includes HTML, CSS, and JavaScript that run in the web browser. These applications
are responsible for rendering the user interface (UI), handling interactions, and often making
asynchronous requests (like using AJAX or Fetch API) to fetch or send data.
Example: A Single Page Application (SPA) built with React.js or Angular.

Server-side Application
A server-side application is executed on a web server. It handles business logic, database
interactions, authentication, and generates dynamic content to be sent to the client. The client
receives HTML pages that are rendered on the server before being sent.
Example: An application built with Express.js, Django, or PHP where most of the logic runs on the
server.

2. Execution Environment
• Client-side:
• Executes in the browser.
• Utilizes the resources (CPU, memory) of the client’s device.
• Dependent on browser compatibility and performance.
• Server-side:
• Executes on a centralized server.
• Uses server resources for processing.
• The same output can be generated regardless of client browser.

3. Technologies Used
• Client-side:
• HTML, CSS, JavaScript
• Frontend frameworks/libraries: React.js, Angular, Vue.js, Svelte
• Server-side:
• Programming languages: JavaScript (Node.js), Python, Java, PHP, Ruby, etc.
• Frameworks: Express.js, Django, Spring, Laravel, Ruby on Rails

4. Responsibilities and Features


Feature / Responsibility Client-side Server-side
UI Rendering Yes Sometimes (SSR)
Business Logic Partial Major
Data Storage LocalStorage, SessionStorage Database (MySQL, MongoDB, etc.)
Authentication Token usage (JWT, OAuth) Token creation, session management
Form Validation Yes (fast, user-friendly) Yes (secure, authoritative)
API Consumption Yes (via AJAX/Fetch) Yes (can serve APIs)
SEO Optimization Limited Excellent (especially with SSR)
Security Less secure More secure

5. Performance Considerations
• Client-side rendering can reduce server load and provide faster interactivity after the initial
load. However, the first page load might be slower due to heavy JavaScript bundles. It also
depends on the client’s hardware.
• Server-side rendering usually delivers fully formed HTML to the browser quickly,
improving perceived load time and SEO. However, it increases the server load and response
time for dynamic pages.

6. Security
Security is a major distinction:
• Client-side:
• Vulnerable to XSS (Cross-Site Scripting) attacks.
• Code is exposed and can be inspected/modified using browser developer tools.
• Should never handle sensitive operations like password hashing or database access.
• Server-side:
• Can implement strong security protocols (authentication, authorization).
• Logic and sensitive data are kept private.
• Vulnerable to server-side attacks like SQL Injection, but easier to manage securely.

7. Scalability and Maintenance


• Client-side applications are easier to scale horizontally since each client runs their own
instance of the logic. However, maintaining consistency across browsers and devices can be
challenging.
• Server-side applications require server scaling, which might involve more cost but are
generally easier to maintain and secure in terms of logic centralization.

8. Examples
Client-side App Example:
A weather forecast SPA built with React fetches real-time data from an API and updates the UI
dynamically without reloading the page.

Server-side App Example:


An e-commerce website built using Node.js and Express renders product pages on the server,
handles cart sessions, and manages payments through server-side APIs.

9. When to Use What?


Use Client-side When:
• You need rich interactivity and responsiveness.
• You are building a SPA with real-time updates.
• SEO is not a critical concern or can be handled with SSR (e.g., Next.js).

Use Server-side When:


• You require strong security and authentication.
• SEO is essential.
• You need to serve data-heavy or dynamic content.
• You want better performance on low-power client devices.

Describe how to set up and use Node.js with NPM to


manage dependencies in a web project.
Introduction
When building modern web applications, developers use many external packages or libraries to
avoid writing everything from scratch. For example, if you want to use a library to make HTTP
requests or create a web server, there’s no need to write it all manually. Instead, you can use Node.js
and its package manager, NPM, to install and manage these libraries efficiently.

1. What is Node.js?
Node.js is a JavaScript runtime environment that allows you to run JavaScript code outside the
browser — on the server or your computer.

Key Features:
• Allows building fast and scalable network applications.
• Used in backend development with frameworks like Express.js.
• Supports file system operations, server creation, databases, etc.

2. What is NPM?
NPM stands for Node Package Manager. It comes installed with Node.js and is used to:
• Install open-source libraries (called packages or modules).
• Manage project dependencies.
• Share your own code with others (if needed).

3. Installing Node.js and NPM


Step 1: Download and Install
• Go to the official website: https://nodejs.org
• Choose the LTS version (Long Term Support) and install it.
• After installation, open your terminal or command prompt and type:

node -v
npm -v

If both commands return version numbers, it means Node.js and NPM are installed successfully.
4. Setting Up a New Web Project
Step 1: Create a Project Folder

mkdir my-web-project
cd my-web-project

Step 2: Initialize the Project with NPM

npm init

This will ask you a series of questions like project name, version, description, etc. You can press
Enter to accept the defaults.

After this, a file called package.json is created.

5. Understanding package.json
The package.json file stores important information about your project:

{
"name": "my-web-project",
"version": "1.0.0",
"description": "A simple web project",
"main": "index.js",
"scripts": {
"start": "node index.js"
},
"dependencies": {},
"devDependencies": {}
}

• scripts: Defines commands you can run (like npm start).

• dependencies: Lists packages your project needs.


• devDependencies: Lists packages needed only for development (e.g., testing tools).

6. Installing Dependencies
Let’s say you want to create a simple web server using Express, a popular Node.js framework.

Step 1: Install Express

npm install express

This does two things:


• Downloads the Express package into a folder called node_modules.
• Adds Express to the dependencies section in package.json.

Step 2: Create a Simple Server


Create a file named index.js:
javascript
CopyEdit
const express = require('express');
const app = express();

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


res.send('Hello, World!');
});

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

Now run your app:


bash
CopyEdit
node index.js

Go to your browser and open http://localhost:3000. You’ll see “Hello, World!”.

7. Using Development Dependencies


Sometimes you need tools only for development, like Nodemon, which restarts your app when you
save changes.
Install it with:
bash
CopyEdit
npm install --save-dev nodemon

Update your scripts section in package.json:

"scripts": {
"start": "node index.js",
"dev": "nodemon index.js"
}

Now run:

npm run dev

Your server will restart automatically whenever you change and save the file — useful during
development!
8. node_modules and package-lock.json
• node_modules/: This folder contains all installed packages. It can be large and is not shared
in code repositories.
• package-lock.json: This file keeps track of the exact version of each installed package. It
ensures consistency when your project is installed on other machines.

9. Sharing Your Project


To share your project:
• Share your code without node_modules/.

• Others can run npm install to install all dependencies based on package.json.

10. Updating and Uninstalling Packages


• Update a package:

npm update package-name

• Uninstall a package:

npm uninstall package-name

Explain the process of serving files using the http


module in Node.js.
Node.js is often used to build servers. One of the core modules it provides is the http module,
which allows us to create a web server without using any external libraries.

1. What is the http Module?


The http module is a built-in Node.js module that helps you create a web server. This server can
listen for requests (like when someone opens your website) and send back responses (like HTML
pages or images).
You don’t need to install anything to use http — it's built into Node.js!
2. Step-by-Step: Creating a Basic Server
Step 1: Create Your Project Folder

mkdir simple-server
cd simple-server

Step 2: Create an HTML File


Create a file called index.html:

<!-- index.html -->


<!DOCTYPE html>
<html>
<head>
<title>My Node Server</title>
</head>
<body>
<h1>Hello from Node.js!</h1>
</body>
</html>

Step 3: Create the Server File


Create a file called server.js:

// server.js
const http = require('http');
const fs = require('fs');
const path = require('path');

// Create the server


const server = http.createServer((req, res) => {
// Set the file path
let filePath = path.join(__dirname, 'index.html');

// Read the file


fs.readFile(filePath, (err, content) => {
if (err) {
res.writeHead(500);
res.end('Server Error');
} else {
// Set headers
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end(content);
}
});
});

// Start the server


server.listen(3000, () => {
console.log('Server is running at http://localhost:3000');
});

Step 4: Run Your Server


node server.js

Open your browser and go to:


http://localhost:3000
You should see your HTML page with “Hello from Node.js!”.

3. Serving Different Files Based on URL


Let’s add more files and use basic routing.

Add More Files


Create a file called about.html:

<!-- about.html -->


<!DOCTYPE html>
<html>
<head>
<title>About Page</title>
</head>
<body>
<h1>This is the About Page</h1>
</body>
</html>

Update your server.js like this:

const http = require('http');


const fs = require('fs');
const path = require('path');

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


let filePath = '';

if (req.url === '/' || req.url === '/index') {


filePath = path.join(__dirname, 'index.html');
} else if (req.url === '/about') {
filePath = path.join(__dirname, 'about.html');
} else {
filePath = path.join(__dirname, '404.html');
}

fs.readFile(filePath, (err, content) => {


if (err) {
res.writeHead(500);
res.end('Server Error');
} else {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end(content);
}
});
});

server.listen(3000, () => {
console.log('Server running at http://localhost:3000');
});
Optional: Create a 404 Page
Create a file called 404.html:

<!-- 404.html -->


<!DOCTYPE html>
<html>
<head>
<title>404</title>
</head>
<body>
<h1>Page Not Found</h1>
</body>
</html>

Now your server shows the correct file based on the URL.

4. How It Works (In Simple Terms)


Here’s what happens when someone visits your site:
1. The HTTP request is sent to your server.
2. Your server checks the URL (like / or /about).

3. Based on the URL, your server reads a file from your computer (like index.html).

4. The server sends back the file content as the HTTP response.
5. The browser displays the page.

5. Serving Static Files (CSS, Images)


If you want to serve CSS or image files, you need to:
• Check the file extension (e.g., .css, .jpg)

• Set the correct Content-Type

Example for CSS:

if (req.url === '/style.css') {


fs.readFile('./style.css', (err, data) => {
if (err) throw err;
res.writeHead(200, { 'Content-Type': 'text/css' });
res.end(data);
});
}

Then, in your HTML:

<link rel="stylesheet" href="/style.css">


Discuss the Express framework and how it simplifies
web server development in Node.js.
Node.js is a powerful platform for building web servers using JavaScript. However, building a web
server using only the built-in http module in Node.js can quickly become complicated as your
project grows. This is where Express.js comes in.

1. What is Express.js?
Express.js is a web application framework for Node.js. It provides tools and features to handle:
• Routing (which URL should return what)
• Middleware (functions that run before sending a response)
• Serving static files (HTML, CSS, images)
• Request and response handling
• Error handling
• Creating REST APIs

Why use Express?


Using the basic http module in Node.js means manually writing code for:

• Reading request URLs


• Matching URLs to responses
• Reading files and setting headers
• Handling form data
Express handles most of this for you with simpler syntax and built-in features.

2. Installing and Setting Up Express


Step 1: Create a Project Folder
bash
CopyEdit
mkdir express-app
cd express-app

Step 2: Initialize a Node.js Project


bash
CopyEdit
npm init -y
Step 3: Install Express
bash
CopyEdit
npm install express

Step 4: Create a Server File


Create a file called server.js:
js
CopyEdit
// server.js
const express = require('express'); // Import Express
const app = express(); // Create an Express app
const port = 3000; // Define the port

// Define a route
app.get('/', (req, res) => {
res.send('Hello from Express!');
});

// Start the server


app.listen(port, () => {
console.log(`Server is running at http://localhost:${port}`);
});

Step 5: Run Your Server


bash
CopyEdit
node server.js

Open your browser and visit: http://localhost:3000


You’ll see: “Hello from Express!”

3. How Express Simplifies Development


✅ 1. Simplified Routing
Instead of writing multiple if statements like in plain Node.js, Express makes routing very easy:
js
CopyEdit
app.get('/about', (req, res) => {
res.send('About Page');
});

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


res.send('Contact Page');
});

• app.get() handles GET requests.

• You can also use app.post(), app.put(), app.delete() for other HTTP methods.
✅ 2. Serving Static Files
To serve HTML, CSS, or image files easily:
js
CopyEdit
app.use(express.static('public'));

Now, put your static files (like index.html, style.css, logo.png) in the public folder.
Express will automatically serve them when requested.
Example:
• http://localhost:3000/style.css will return public/style.css

✅ 3. Middleware Support
Middleware are functions that run between the request and response.
For example, to log every request:
js
CopyEdit
app.use((req, res, next) => {
console.log(`${req.method} ${req.url}`);
next(); // Pass control to the next handler
});

Middleware helps with:


• Logging
• Parsing data
• Authentication
• Error handling

✅ 4. Parsing Form Data


To handle form submissions, you can use built-in middleware:
js
CopyEdit
app.use(express.urlencoded({ extended: true }));
app.use(express.json());

Now you can easily access form data from req.body.

4. Express in Real Projects


Express is commonly used in:
• Building REST APIs (sending JSON data)
• Creating full-stack apps (with React, Angular, or Vue)
• Backend systems for mobile apps
• E-commerce and blogs
• Real-time chat apps (with Socket.io)

5. Example: Simple REST API with Express


js
CopyEdit
app.get('/api/products', (req, res) => {
const products = [
{ id: 1, name: 'Pen' },
{ id: 2, name: 'Notebook' },
];
res.json(products);
});

Go to http://localhost:3000/api/products
You’ll see a JSON response with product data.

Discuss the benefits and challenges of using server-side


rendering with templating engines in Node.js
When you build a web application, you need to decide where the web pages are created — on the
server or in the browser. One common method is Server-Side Rendering (SSR), where the HTML
is generated on the server and sent to the user's browser.
To make SSR easier, developers often use templating engines like EJS, Pug, or Handlebars in
Node.js. These engines allow you to build dynamic web pages using templates.

1. What is Server-Side Rendering (SSR)?


Server-Side Rendering means that the server (Node.js) creates a complete HTML page before
sending it to the browser.

How it works (simple flow):


1. The user requests a web page (e.g., /home).

2. The Node.js server processes the request.


3. The server uses a template file to generate HTML.
4. The server sends the ready-made HTML to the browser.
5. The browser displays the page.
2. What is a Templating Engine?
A templating engine allows you to create HTML templates that include dynamic data. You don’t
need to write the full HTML manually every time.

Popular templating engines in Node.js:


• EJS (Embedded JavaScript)
• Pug (formerly Jade)
• Handlebars
With these, you can write something like:

<!-- example.ejs -->


<h1>Welcome <%= userName %></h1>

In your server:

res.render('example', { userName: 'Alice' });

The final HTML becomes:

<h1>Welcome Alice</h1>

3. Benefits of Server-Side Rendering with Templating Engines


✅ 1. Faster First Page Load (Better Performance)
• The server sends a fully rendered HTML page, so users see the content faster.
• No need to wait for JavaScript to load before the page appears.

✅ 2. Better SEO (Search Engine Optimization)


• Search engines like Google can easily read and index server-rendered pages.
• Important for blogs, product pages, and business websites.

✅ 3. Easier for Beginners


• Templating engines are simple to use.
• You can quickly build pages using templates and fill them with data.

✅ 4. Centralized Control
• All logic and rendering happen on the server.
• Easier to manage when working with data from a database.
✅ 5. Reusable Templates
• Create a base layout and reuse it for different pages.
• This keeps your code clean and reduces duplication.
Example of a layout (EJS):

<!-- layout.ejs -->


<html>
<body>
<%- body %>
</body>
</html>

4. Challenges of Server-Side Rendering


❌ 1. More Server Load
• The server must generate the HTML for every request.
• If your site has many users, this can slow down the server.

❌ 2. Slower Interactions After Page Load


• After the initial page load, if users click around, it may reload the whole page again.
• Unlike client-side rendering (with React or Vue), SSR doesn't provide smooth, app-like
interactions.

❌ 3. Harder to Build Rich UI


• If your app needs a lot of dynamic user interactions (drag, drop, real-time updates), SSR is
not enough.
• You’ll need to mix SSR with front-end JavaScript.

❌ 4. Requires Learning a Templating Language


• You need to learn how to use a templating engine like EJS or Pug.
• It's simple, but still something new to learn.

❌ 5. Less Suitable for Single Page Applications (SPA)


• For highly interactive applications, SSR might not be the best choice.
• SPAs built with React or Angular offer smoother user experiences for such cases.

5. Example: SSR with EJS in Node.js


Let’s look at a simple example:
Step 1: Install Express and EJS

npm install express ejs

Step 2: Set up the server

const express = require('express');


const app = express();
const port = 3000;

// Set EJS as the templating engine


app.set('view engine', 'ejs');

// Route to render a page


app.get('/', (req, res) => {
res.render('home', { title: 'My Website', message: 'Hello from EJS!' });
});

app.listen(port, () => {
console.log(`Server running at http://localhost:${port}`);
});

Step 3: Create a template


Create a folder called views, and inside it, create a file named home.ejs:

<!-- views/home.ejs -->


<!DOCTYPE html>
<html>
<head>
<title><%= title %></title>
</head>
<body>
<h1><%= message %></h1>
</body>
</html>

Now, when you visit http://localhost:3000, you’ll see the rendered HTML page.

Discuss how you can use Express and a templating


engine to serve dynamic content.
When building websites with Node.js, you often want to show different content to different users.
For example:
• Showing a user’s name after they log in.
• Displaying products from a database.
• Rendering a blog page with multiple posts.
This is called dynamic content — content that changes based on data.
To serve dynamic content in Node.js, we can use:
1. Express – a web framework for building servers.
2. Templating Engine – a tool that helps create HTML pages using variables.
Let’s walk through how to use them together in a simple and easy way.

What Is Dynamic Content?


Static content = Always the same (e.g., plain index.html file).
Dynamic content = Changes depending on data (e.g., user's name, products list, messages).

Example:
Static:

<h1>Welcome!</h1>

Dynamic:

<h1>Welcome, Alice!</h1>

We need some way to insert the name "Alice" into the HTML. That’s where a templating engine
comes in.

1. Setting Up Express and EJS


We’ll use EJS (Embedded JavaScript) as the templating engine because it's easy to learn and works
great with Express.

✅ Step 1: Create the Project

mkdir express-dynamic
cd express-dynamic
npm init -y

✅ Step 2: Install Express and EJS

npm install express ejs

✅ Step 3: Create the Basic Server


Create a file called server.js:

const express = require('express');


const app = express();
const port = 3000;

// Set EJS as the templating engine


app.set('view engine', 'ejs');
// Route to home page
app.get('/', (req, res) => {
const userName = 'Alice';
res.render('home', { name: userName });
});

app.listen(port, () => {
console.log(`Server running at http://localhost:${port}`);
});

2. Create an EJS Template


Create a folder named views, and inside it, create a file named home.ejs:

<!-- views/home.ejs -->


<!DOCTYPE html>
<html>
<head>
<title>Dynamic Page</title>
</head>
<body>
<h1>Hello, <%= name %>!</h1>
</body>
</html>

🧠 What’s Happening Here?


• <%= name %> is EJS syntax to insert a variable.

• res.render('home', { name: userName }) sends data from the server to the


template.
• The template renders the final HTML and sends it to the browser.
Now open your browser and go to:
http://localhost:3000
You’ll see:
“Hello, Alice!”

3. Serving Lists and More Data


You can also send arrays and objects to the template.

📝 Example: List of Products


In server.js:

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


const products = [
{ name: 'Pen', price: 10 },
{ name: 'Notebook', price: 50 },
{ name: 'Pencil', price: 5 }
];
res.render('products', { products: products });
});

In views/products.ejs:

<!DOCTYPE html>
<html>
<head>
<title>Product List</title>
</head>
<body>
<h1>Products</h1>
<ul>
<% products.forEach(product => { %>
<li><%= product.name %> - Rs. <%= product.price %></li>
<% }); %>
</ul>
</body>
</html>

Result in Browser:

Products
- Pen - Rs. 10
- Notebook - Rs. 50
- Pencil - Rs. 5

This is dynamic content: the page is changing based on the data sent from the server.

4. Benefits of Using Express with EJS


✅ Easy to use and understand
• No complex JavaScript required
• Syntax is close to HTML

✅ Reuse templates
You can create a layout file (like a master page) and reuse it for many pages.

✅ Clean separation of logic and design


• Business logic stays in the .js file

• UI stays in .ejs templates

5. Folder Structure
Here’s how your project might look:
express-dynamic/

├── server.js
├── package.json
└── views/
├── home.ejs
└── products.ejs

Later, you can also create a public/ folder for CSS and images.

Explain how you can fetch JSON data from an API


using the fetch function in JavaScript.
In modern web development, websites often need to get data from external sources like APIs. This
could be weather information, user data, product listings, or anything else stored on a remote server.
To get that data, JavaScript provides a built-in function called fetch(). It allows you to make a
request to a server and receive a response, often in JSON format.
Let’s break this down step-by-step in a simple and beginner-friendly way.

1. What is an API?
API stands for Application Programming Interface. In web development, it usually means a
URL you can access to get or send data.
Example of a public API:
https://jsonplaceholder.typicode.com/users
This API returns a list of users in JSON format.

2. What is JSON?
JSON (JavaScript Object Notation) is a way to store and exchange data. It looks like JavaScript
objects.
Example:

{
"name": "Alice",
"age": 25,
"email": "[email protected]"
}

JSON is easy for both humans and computers to read. That’s why many APIs use it to send and
receive data.
3. What is fetch() in JavaScript?
The fetch() function lets you make HTTP requests in JavaScript.

Basic syntax:

fetch(url)
.then(response => response.json())
.then(data => {
// use the data here
})
.catch(error => {
// handle any errors
});

Let’s break this down step-by-step.

4. Step-by-Step: How to Fetch JSON Data


✅ Step 1: Choose an API URL
We’ll use a free example API:

https://jsonplaceholder.typicode.com/users

It gives us fake user data in JSON format.

✅ Step 2: Use fetch() to Make the Request

<!DOCTYPE html>
<html>
<head>
<title>Fetch Example</title>
</head>
<body>
<h1>User List</h1>
<ul id="userList"></ul>

<script>
// Step 1: Fetch data from API
fetch('https://jsonplaceholder.typicode.com/users')
.then(response => response.json()) // Step 2: Convert response to JSON
.then(data => {
// Step 3: Use the data
const userList = document.getElementById('userList');
data.forEach(user => {
const li = document.createElement('li');
li.textContent = user.name + ' - ' + user.email;
userList.appendChild(li);
});
})
.catch(error => {
console.error('Error fetching data:', error);
});
</script>
</body>
</html>

5. Explanation of Each Part


🔹 fetch('https://jsonplaceholder.typicode.com/users')
This sends a GET request to the given URL to fetch data.

🔹 .then(response => response.json())


When the server responds, this part reads the response and converts it to JSON.
response.json() returns another promise, which gives us the actual data.

🔹 .then(data => { ... })


Once we get the JSON data, we use it inside this block. data is usually an array of objects.

🔹 data.forEach(...)
We loop through each user object and display their name and email in an unordered list (<ul>).

🔹 .catch(error => { ... })


This catches any errors — like if the internet connection fails or the API doesn’t work.

6. Example JSON Data Returned


From this API:

[
{
"id": 1,
"name": "Leanne Graham",
"email": "[email protected]"
},
{
"id": 2,
"name": "Ervin Howell",
"email": "[email protected]"
}
]
You can access individual fields like:
• user.name
• user.email

7. Why Use fetch()?


✅ Easy and built into JavaScript
You don’t need to install anything.

✅ Works with modern browsers


fetch() is supported in most modern browsers.

✅ Returns promises
It fits well with async/await and modern JavaScript coding styles.

8. Bonus: Using Async/Await (Simpler Syntax)


Instead of using .then(), you can use async/await:

async function loadUsers() {


try {
const response = await fetch('https://jsonplaceholder.typicode.com/users');
const data = await response.json();

const userList = document.getElementById('userList');


data.forEach(user => {
const li = document.createElement('li');
li.textContent = `${user.name} - ${user.email}`;
userList.appendChild(li);
});
} catch (error) {
console.error('Error:', error);
}
}

loadUsers();

This version works the same but looks cleaner and is easier to read.

Discuss the NPM package management system in detail.


When building projects with Node.js, developers often don’t want to write every piece of code from
scratch. Instead, they use ready-made tools and libraries created by other developers. These tools
are called packages, and the system used to manage them is called NPM.
What is NPM?
NPM stands for Node Package Manager.
It is:
• A tool that helps you install, update, and remove packages (libraries/tools) in your Node.js
project.
• A website (https://www.npmjs.com) where you can search for and learn about different
packages.
• A registry that stores thousands of packages (free and open-source code).

Example Packages:
• express – used to build web servers.

• mongoose – used to connect with MongoDB.

• axios – used to make HTTP requests.

• nodemon – used during development to automatically restart your server when files
change.

Why Use NPM?


NPM saves time and effort. Instead of writing everything from zero, you can use tried and tested
code from others.

✅ Benefits:
• Access to thousands of open-source tools.
• Easily manage project dependencies.
• Keep your code clean and organized.
• Get updates and bug fixes easily.

Getting Started with NPM


Before using NPM, make sure you have Node.js installed. NPM comes automatically with Node.js.
To check if Node.js and NPM are installed:
bash
CopyEdit
node -v
npm -v

You’ll see version numbers if both are installed.


1. Initialize a Project with NPM
To use NPM in a project, first create a folder and run:
bash
CopyEdit
npm init

This will ask you a few questions:


• Project name
• Version
• Description
• Entry point (index.js)

• Author, license, etc.


After that, it will create a file named package.json.

package.json example:
json
CopyEdit
{
"name": "myapp",
"version": "1.0.0",
"main": "index.js",
"dependencies": {}
}

This file:
• Describes your project.
• Keeps track of installed packages.
• Makes it easy to share your project with others.

2. Installing Packages
To install a package, use:
bash
CopyEdit
npm install package-name

Example:
bash
CopyEdit
npm install express

This:
• Downloads the express package.

• Adds it to a folder called node_modules.

• Updates the package.json and adds the package to dependencies.

Now you can use it in your code:


js
CopyEdit
const express = require('express');

3. Development vs. Production Packages


Some packages are only needed during development.
Use the --save-dev flag:
bash
CopyEdit
npm install nodemon --save-dev

This adds nodemon to devDependencies instead of dependencies.

Difference:
• dependencies = Needed in production (live project).

• devDependencies = Needed only during development.

4. Understanding node_modules and package-lock.json


• node_modules/ is the folder where all installed packages are stored.

• package-lock.json is a file that keeps track of the exact versions of each package and
their sub-packages.
These files help keep the project consistent across different computers.

5. Using Installed Packages


Example: After installing chalk, you can use it to color your console text.

Step 1: Install
bash
CopyEdit
npm install chalk
Step 2: Use in Code
js
CopyEdit
const chalk = require('chalk');
console.log(chalk.green("This is green text!"));

6. Updating and Removing Packages


✅ To update a package:
bash
CopyEdit
npm update package-name

✅ To remove a package:
bash
CopyEdit
npm uninstall package-name

7. Installing All Packages From package.json


If someone gives you a project with a package.json file, run:
bash
CopyEdit
npm install

This will install all the packages listed in the file automatically.

8. Publishing Your Own Package (Optional)


Advanced step: You can even create your own NPM package and publish it to the NPM registry.
Steps include:
1. Create your package
2. Run npm login (you need an NPM account)

3. Run npm publish

Then others can install your package with:


bash
CopyEdit
npm install your-package-name
9. Common NPM Commands Summary
Command Purpose
npm init Start a new project
npm install package Install a package
npm install package --save-dev Install dev-only package
npm uninstall package Remove a package
npm update Update installed packages
npm install Install all dependencies from package.json
npm list Show installed packages

Discuss about the routing in Express, handle HTTP


methods and create route parameters.
When building websites and APIs, routing is how you tell the server what to do when a user goes
to a certain URL. For example:
• Go to /about → show "About Us" page

• Go to /products → show list of products

• Go to /users/123 → show user with ID 123

In Express.js (a Node.js framework), routing is simple and powerful.

What is Routing in Express?


Routing means defining different URLs (routes) and how the server should respond when a
client visits those URLs.

const express = require('express');


const app = express();

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


res.send('Welcome to the Home Page!');
});

When a user goes to http://localhost:3000/, they will see:


"Welcome to the Home Page!"

Handling Different HTTP Methods


Web servers handle different types of HTTP methods. The most common ones are:
Method Use
GET To get/read data (e.g., show a page)
POST To send new data (e.g., submit a form)
PUT To update existing data
DELETE To delete data

💡 Each method has its own Express function:


• app.get()
• app.post()
• app.put()
• app.delete()
Let’s look at examples for each.

✅ GET Request

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


res.send('Hello there!');
});

This responds when someone visits the URL /hello.

✅ POST Request

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


res.send('Form submitted!');
});

This is used when someone sends data, like from a form.

✅ PUT Request

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


res.send('Data updated!');
});

Used to update data (e.g., edit a user profile).

✅ DELETE Request

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


res.send('Data deleted!');
});
Used to delete something (like a post or comment).

🧵 Route Parameters in Express


Sometimes, your route needs to take dynamic values from the URL. For example:
• /users/123
• /products/456
In this case, we use route parameters.

💡 How to write it:

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


const userId = req.params.id;
res.send(`You requested user with ID: ${userId}`);
});

If you visit http://localhost:3000/users/123, you’ll see: "You requested user with


ID: 123"

🔄 Multiple Route Parameters


You can have more than one parameter:

app.get('/posts/:postId/comments/:commentId', (req, res) => {


const postId = req.params.postId;
const commentId = req.params.commentId;
res.send(`Post ID: ${postId}, Comment ID: ${commentId}`);
});

Example URL:
/posts/10/comments/5
→ Shows: "Post ID: 10, Comment ID: 5"

✨ Real-Life Example: User Profile Page


Imagine you have a user website.

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


const username = req.params.username;
res.send(`Welcome to ${username}'s profile`);
});

URL: /profile/alice
Response: "Welcome to alice's profile"
📂 Common Folder Structure
Here’s what your Express project might look like:

my-app/
├── node_modules/
├── app.js (or server.js)
├── package.json

And your app.js might look like:

const express = require('express');


const app = express();
const port = 3000;

// Home page
app.get('/', (req, res) => {
res.send('Home Page');
});

// About page
app.get('/about', (req, res) => {
res.send('About Page');
});

// Dynamic user route


app.get('/users/:id', (req, res) => {
res.send(`User ID: ${req.params.id}`);
});

app.listen(port, () => {
console.log(`Server is running at http://localhost:${port}`);
});

🧪 Testing Your Routes


1. Run your server:

node app.js

2. Open your browser and try:


• http://localhost:3000/
• http://localhost:3000/about
• http://localhost:3000/users/5
3. You’ll see the matching text responses.

🧼 Good Practices
• Use meaningful names in route paths: /users/:userId is better than /u/:x
• Keep routes organized using separate files (like routes/users.js) as your app grows.

• Use middleware to handle request data, errors, and authentication (optional for now).

Discuss how to use middleware for error handling and


send appropriate error messages to clients.

🧠 What is Error Handling?


Error handling means catching and managing errors that occur in your application, so you can:
• Prevent crashes
• Give users helpful feedback
• Log issues for debugging
• Return proper HTTP status codes
In Express.js, we use error-handling middleware to catch and respond to errors in a clean and
centralized way.

🚦 What is Middleware Again?


Middleware is any function that sits between the request and the response in Express. It's used to:
• Log requests
• Authenticate users
• Parse data
• And handle errors ✅

💥 Types of Errors in Express


Error Type Example
Synchronous errors Throwing an error in a route
Asynchronous errors Errors from async/await or Promises
Route not found 404 - user requested a route that doesn't exist
Database errors Failing to connect or query data

🧪 Simple Example Without Error Middleware


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

This will crash the app unless you handle it properly.

✅ How to Use Error Handling Middleware in Express


🔹 Step 1: Add an Error Handler
Error-handling middleware in Express must have four arguments:
js
CopyEdit
(err, req, res, next)

javascript
CopyEdit
// Error handling middleware
app.use((err, req, res, next) => {
console.error(err.stack); // Log error in the console
res.status(500).json({ message: 'Something went wrong!', error:
err.message });
});

This should be added after all routes and middleware.

🔹 Step 2: Triggering Errors


You can throw errors manually using:
javascript
CopyEdit
// Synchronous error
throw new Error('Manual error');

Or in async functions:
javascript
CopyEdit
app.get('/user', async (req, res, next) => {
try {
// simulate database failure
throw new Error('Database not available');
} catch (err) {
next(err); // pass error to error middleware
}
});

🔍 Handling 404 (Not Found) Errors


Create a middleware that handles unknown routes:
javascript
CopyEdit
// 404 Middleware
app.use((req, res, next) => {
res.status(404).json({ message: 'Route not found' });
});

Make sure this comes after all your routes.

🌟 Full Example: Express App with Error Middleware


javascript
CopyEdit
const express = require('express');
const app = express();

app.use(express.json());

// Example route
app.get('/divide', (req, res, next) => {
try {
const { a, b } = req.query;
if (!b || b == 0) throw new Error('Division by zero not allowed');

const result = Number(a) / Number(b);


res.json({ result });
} catch (err) {
next(err);
}
});

// 404 middleware
app.use((req, res, next) => {
res.status(404).json({ message: 'Route not found' });
});

// Error handling middleware


app.use((err, req, res, next) => {
console.error('Error:', err.message);
res.status(500).json({
message: 'Internal Server Error',
error: err.message
});
});

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

Illustrate the integration of databases with Express.js


with suitable example.
🧠 What is a Database?
A database stores data for your application. Instead of keeping data in memory (which is lost when
the server restarts), a database lets you store data permanently.

Common databases with Node.js:


Type Examples
SQL MySQL, PostgreSQL
NoSQL MongoDB ✅
We’ll use MongoDB because it's beginner-friendly and flexible with JSON-like data.

📦 Tools Used
• Node.js – JavaScript runtime
• Express.js – Web framework
• MongoDB Atlas – Free cloud MongoDB database
• Mongoose – MongoDB library for Node.js

📁 Project Setup
🔧 Step 1: Initialize Project
bash
CopyEdit
mkdir express-mongo-app
cd express-mongo-app
npm init -y
npm install express mongoose

📄 Step 2: Folder Structure


markdown
CopyEdit
express-mongo-app/
├── app.js
└── models/
└── User.js

✏️Step 3: Create MongoDB Account (If You Don’t Have One)


1. Visit https://www.mongodb.com/cloud/atlas
2. Create a free account
3. Create a cluster
4. Add a user and password
5. Get your connection string (something like):
bash
CopyEdit
mongodb+srv://<username>:<password>@cluster0.mongodb.net/mydb?
retryWrites=true&w=majority

🔌 Step 4: Create Mongoose Model


models/User.js
javascript
CopyEdit
const mongoose = require('mongoose');

const userSchema = new mongoose.Schema({


name: String,
email: String,
age: Number
});

module.exports = mongoose.model('User', userSchema);

🚀 Step 5: Build Express Server with MongoDB


app.js
javascript
CopyEdit
const express = require('express');
const mongoose = require('mongoose');
const User = require('./models/User');

const app = express();


app.use(express.json()); // Middleware to parse JSON

// Connect to MongoDB
mongoose.connect('your-mongodb-uri-here', {
useNewUrlParser: true,
useUnifiedTopology: true
}).then(() => console.log('MongoDB Connected'))
.catch(err => console.log(err));

// Create a new user (POST)


app.post('/users', async (req, res) => {
try {
const user = await User.create(req.body);
res.status(201).json(user);
} catch (err) {
res.status(400).json({ message: err.message });
}
});

// Get all users (GET)


app.get('/users', async (req, res) => {
const users = await User.find();
res.json(users);
});

// Get single user by ID (GET)


app.get('/users/:id', async (req, res) => {
const user = await User.findById(req.params.id);
if (!user) return res.status(404).json({ message: 'User not found' });
res.json(user);
});

// Update a user (PUT)


app.put('/users/:id', async (req, res) => {
const user = await User.findByIdAndUpdate(req.params.id, req.body, { new: true
});
res.json(user);
});

// Delete a user (DELETE)


app.delete('/users/:id', async (req, res) => {
await User.findByIdAndDelete(req.params.id);
res.json({ message: 'User deleted' });
});

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

🧪 Test Your API (Using Postman or curl)


➕ Create User
bash
CopyEdit
POST /users
{
"name": "Alice",
"email": "[email protected]",
"age": 25
}

📥 Get All Users


bash
CopyEdit
GET /users

🖊 Update User
bash
CopyEdit
PUT /users/<user-id>
{
"name": "Alice Updated"
}
❌ Delete User
bash
CopyEdit
DELETE /users/<user-id>

Explain the following methods in Express:


(i) res.send()
(ii) res.json()

(i) res.send()
✅ What it does:
• res.send() is used to send a response back to the client.

• It can send a string, HTML, object, array, or Buffer.


• It automatically sets the correct Content-Type based on the data.

🧠 Syntax:
javascript
CopyEdit
res.send(body)

📦 Examples:
javascript
CopyEdit
// Send a simple string
res.send('Hello World');

// Send an HTML page


res.send('<h1>Welcome</h1>');

// Send an object
res.send({ name: 'Alice', age: 25 });

When you send an object, res.send() internally converts it to JSON — but for clarity and best
practice, we use res.json() for that (explained below).

🧾 (ii) res.json()
✅ What it does:
• res.json() sends a JSON-formatted response.
• It is the preferred method for APIs.
• Automatically sets the Content-Type: application/json header.

🧠 Syntax:
javascript
CopyEdit
res.json(data)

📦 Examples:
javascript
CopyEdit
// Send a JSON object
res.json({ success: true, message: 'Data received' });

// Send an array
res.json([1, 2, 3]);

// Send nested data


res.json({
user: { id: 1, name: 'John' },
status: 'active'
});

🔍 Difference Between res.send() and res.json()


Feature res.send() res.json()
Sends Any type (string, object, HTML, etc) JSON only
Sets content-type Auto-detects (text/html, etc.) Always sets to application/json
Best used for Text or HTML responses API responses with JSON

✅ Which One to Use?


• Use res.send() when sending plain text or HTML.

• Use res.json() when sending data in JSON format, especially for APIs.

Example in an Express App


javascript
CopyEdit
app.get('/hello', (req, res) => {
res.send('Hello, welcome to our site!');
});

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


res.json({ id: 1, name: 'Alice' });
});
Discuss using middleware and session management,
including JSON Web Tokens (JWT) for secure
authentication

What is Middleware?
🔹 Definition:
Middleware in Express.js is a function that runs between the request and the response. It can:
• Modify the request or response
• End the request-response cycle
• Call the next middleware function

🔹 Example:
javascript
CopyEdit
function logger(req, res, next) {
console.log(`${req.method} ${req.url}`);
next(); // move to the next middleware or route
}

app.use(logger);

This middleware logs every request made to the server.

🔐 Why Use Middleware in Authentication?


Middleware is essential for:
• Protecting routes (checking if a user is logged in)
• Verifying JWT tokens
• Parsing request bodies or cookies

🧰 Common Middleware in Authentication:


Middleware Purpose
express.json() Parse JSON body of requests
cookie-parser Parse cookies
jsonwebtoken (JWT) Verify authentication token
Custom middleware Check if the user is authenticated
🔐 Session Management
Session management means keeping track of users between requests. This is important because
HTTP is stateless — each request is independent.

Two popular ways:


1. Sessions (with cookies)
2. JWT (token-based authentication) ✅ recommended for APIs

🔑 JSON Web Tokens (JWT)


🔹 What is JWT?
JWT is a secure way to transmit user data between client and server as a token.

🔹 How it Works:
1. User logs in → Server checks credentials
2. If valid → Server sends a signed JWT
3. On future requests, client sends token in the Authorization header
4. Server verifies the token and allows or denies access

🔐 JWT Structure
A JWT has 3 parts (all base64 encoded):
css
CopyEdit
header.payload.signature

Example:
CopyEdit
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.
eyJ1c2VySWQiOjEyMywibmFtZSI6IkpvaG4ifQ.
k2uW5bPzi4WqgTqtKmWnPdsTh7YtN2hH5o5NBYUZIiY

🔨 Implementing JWT Authentication in Express

✅ Step 1: Install Packages


bash
CopyEdit
npm install express jsonwebtoken bcryptjs
• express – server

• jsonwebtoken – to sign/verify tokens

• bcryptjs – to hash passwords

✅ Step 2: Basic Authentication Flow


javascript
CopyEdit
// app.js
const express = require('express');
const jwt = require('jsonwebtoken');
const bcrypt = require('bcryptjs');

const app = express();


app.use(express.json());

const USERS = []; // Store users in-memory (for demo only)

// Secret key for signing JWT (use .env in real apps)


const JWT_SECRET = 'mysecretkey';

// Register Route
app.post('/register', async (req, res) => {
const { username, password } = req.body;

// Hash password
const hashedPassword = await bcrypt.hash(password, 10);

USERS.push({ username, password: hashedPassword });

res.send('User registered');
});

// Login Route
app.post('/login', async (req, res) => {
const { username, password } = req.body;
const user = USERS.find(u => u.username === username);

if (!user || !(await bcrypt.compare(password, user.password))) {


return res.status(401).send('Invalid credentials');
}

// Create JWT token


const token = jwt.sign({ username }, JWT_SECRET, { expiresIn: '1h' });

res.json({ token });


});

✅ Step 3: Middleware to Protect Routes


javascript
CopyEdit
function authenticateToken(req, res, next) {
const authHeader = req.headers['authorization'];
const token = authHeader && authHeader.split(' ')[1];
if (!token) return res.sendStatus(401);

jwt.verify(token, JWT_SECRET, (err, user) => {


if (err) return res.sendStatus(403);
req.user = user; // save user info in request
next();
});
}

// Protected Route
app.get('/profile', authenticateToken, (req, res) => {
res.send(`Hello ${req.user.username}, this is your profile`);
});

✅ Step 4: Start the Server


javascript
CopyEdit
app.listen(3000, () => {
console.log('Server running on http://localhost:3000');
});

🧪 Test the Flow


1. Register a user
bash
CopyEdit
curl -X POST http://localhost:3000/register -H "Content-Type: application/json"
-d '{"username":"john", "password":"1234"}'

2. Login
bash
CopyEdit
curl -X POST http://localhost:3000/login -H "Content-Type: application/json" -d
'{"username":"john", "password":"1234"}'

You’ll get a token like:


json
CopyEdit
{ "token": "eyJhbGci..." }

3. Access Protected Route


bash
CopyEdit
curl http://localhost:3000/profile -H "Authorization: Bearer <your-token>"
Discuss how you would use the async/await syntax to
fetch data from a remote API and render it dynamically
in an Express application.

🧠 What is async/await?
async/await is a modern way to work with asynchronous code in JavaScript.

• async makes a function return a Promise.

• await makes JavaScript wait for the promise to resolve.

It helps write cleaner and more readable code when dealing with asynchronous operations like API
calls, file reading, or database queries.

📦 Tools Required
• Node.js (Install from nodejs.org)
• Express.js (Web framework for Node.js)
• Axios or Fetch (to call external APIs)
• EJS (a simple template engine to render HTML dynamically)

📁 Project Structure
go
CopyEdit
my-app/
├── views/
│ └── users.ejs
├── app.js
├── package.json

Step-by-Step Guide

✅ Step 1: Initialize a Node.js Project


bash
CopyEdit
mkdir my-app
cd my-app
npm init -y
✅ Step 2: Install Required Packages
bash
CopyEdit
npm install express axios ejs

• express → To build the server

• axios → To fetch data from an API

• ejs → For rendering HTML dynamically

✅ Step 3: Create app.js


This is your main server file.
javascript
CopyEdit
// app.js

const express = require('express');


const axios = require('axios');
const app = express();

// Set EJS as the view engine


app.set('view engine', 'ejs');

// Route to fetch and display users


app.get('/users', async (req, res) => {
try {
// Fetch user data from a public API
const response = await
axios.get('https://jsonplaceholder.typicode.com/users');

// Send the data to the EJS template


res.render('users', { users: response.data });

} catch (error) {
console.error('Error fetching data:', error.message);
res.status(500).send('Error fetching data from API');
}
});

// Start the server


const PORT = 3000;
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});

✅ Step 4: Create the EJS View


Create a folder called views, and inside it, create users.ejs:
html
CopyEdit
<!-- views/users.ejs -->

<!DOCTYPE html>
<html>
<head>
<title>User List</title>
</head>
<body>
<h1>List of Users</h1>
<ul>
<% users.forEach(user => { %>
<li><strong><%= user.name %></strong> - <%= user.email %></li>
<% }); %>
</ul>
</body>
</html>

✅ Step 5: Run the Application


bash
CopyEdit
node app.js

Now, open your browser and go to:


👉 http://localhost:3000/users
You should see a list of users dynamically loaded from the API.

🧠 Understanding What’s Happening


🔁 Asynchronous Flow with async/await
1. When a user visits /users, Express runs the handler.

2. Inside that route handler, we use axios.get() to call the API.

3. Since axios.get() returns a promise, we use await to pause the function until the data
is returned.
4. After data is fetched, we send it to the view (users.ejs) using res.render.

5. In the EJS file, we loop through the array and show user names and emails.

✅ Why Use async/await Instead of Callbacks or


.then()?
Here’s a comparison:

❌ Using .then():
javascript
CopyEdit
axios.get('https://api.com/data')
.then(response => {
// handle data
})
.catch(error => {
// handle error
});

✅ Using async/await:
javascript
CopyEdit
try {
const response = await axios.get('https://api.com/data');
// handle data
} catch (error) {
// handle error
}

• async/await looks like regular code.

• Easier to read, especially with multiple asynchronous calls.

Error Handling
Always use try...catch with await to handle errors gracefully. If the API is down or returns
an error, the catch block prevents your app from crashing and shows a meaningful message.

Explain how you can deploy a Node.js application with


Express to a production.
✅ 1. Prepare Your Application
Before deployment, make sure:
• Your app runs without errors.
• You have a package.json file with necessary dependencies.

• You’ve tested it locally (node app.js or npm start).

🧾 Example File Structure:


java
CopyEdit
my-app/
├── app.js
├── package.json
├── routes/
├── views/
└── public/

✅ 2. Choose a Hosting Service


Popular platforms for hosting Node.js apps:
• Render (easy & beginner-friendly)
• Railway (easy)
• Vercel (mainly for front-end, not backend)
• Heroku (used to be popular but limited free tier)
• DigitalOcean or AWS (more control, less beginner-friendly)
For this guide, let’s use Render (free and easy).

🚀 Deploy to Render.com (Beginner-Friendly)


✅ Step 1: Push Your Code to GitHub
Render requires your code to be on GitHub.
• Go to https://github.com
• Create a new repository (e.g., my-express-app)

• Push your project using Git:


bash
CopyEdit
git init
git add .
git commit -m "Initial commit"
git remote add origin https://github.com/yourusername/my-express-app.git
git push -u origin main

✅ Step 2: Create an Account on Render


• Go to https://render.com
• Sign in with GitHub

✅ Step 3: Create a New Web Service


• Click "New" → "Web Service"
• Connect your GitHub repo
• Choose the repo with your app
Fill in the settings:
• Name: my-express-app
• Build Command:
nginx
CopyEdit
npm install

• Start Command:
nginx
CopyEdit
node app.js

• Environment: Node

• Region: Closest to your users


Click "Create Web Service".

✅ Step 4: Wait and Test


Render will install your app and start it.
When done, you'll get a live URL like:
👉 https://my-express-app.onrender.com

Visit it in your browser!

Develop a Node.js program that reads the contents of a


text file and writes the same content to another text file.
// Import the built-in 'fs' module
const fs = require('fs');

// Define source and destination file paths


const sourceFile = 'source.txt';
const destinationFile = 'destination.txt';

// Read the contents of the source file


fs.readFile(sourceFile, 'utf8', (readErr, data) => {
if (readErr) {
console.error(`Error reading from ${sourceFile}:`, readErr.message);
return;
}

// Write the content to the destination file


fs.writeFile(destinationFile, data, (writeErr) => {
if (writeErr) {
console.error(`Error writing to ${destinationFile}:`, writeErr.message);
return;
}

console.log(`Content successfully copied from ${sourceFile} to ${destinationFile}`);


});
});

Write a Node.js program to create a basic HTTP server


that listens on port 3000 and returns a "Hello World!"
message when accessed via a browser or a tool like curl.
// Import the built-in 'http' module
const http = require('http');

// Define the port number


const PORT = 3000;

// Create the HTTP server


const server = http.createServer((req, res) => {
// Set the response status and headers
res.writeHead(200, { 'Content-Type': 'text/plain' });

// Send the response body


res.end('Hello World!\n');
});

// Start listening on port 3000


server.listen(PORT, () => {
console.log(`Server is running at http://localhost:${PORT}`);
});
💡 How to Run:
Save the file as server.js.

Open your terminal and run:

bash
Copy
Edit
node server.js
Open your browser and go to:
👉 http://localhost:3000

Write a express program to handle different HTTP


methods (GET, POST) on different routes.
// Import the express module
const express = require('express');

// Create an Express application


const app = express();

// Middleware to parse JSON data from requests


app.use(express.json());

// Define a port for the server


const PORT = 3000;
// -------------------- GET Route --------------------
// Route: GET /hello
// Description: Responds with a welcome message
app.get('/hello', (req, res) => {
res.send('Hello! This is a GET request.');
});

// -------------------- POST Route --------------------


// Route: POST /submit
// Description: Accepts JSON data and responds with a message
app.post('/submit', (req, res) => {
const userData = req.body;
res.send(`POST request received. Data submitted: ${JSON.stringify(userData)}`);
});
// Start the server
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});

You might also like