0% found this document useful (0 votes)
1 views18 pages

Web Project

The document provides various examples of Node.js and Express.js code snippets demonstrating functionalities such as displaying messages in the browser, handling HTTP requests, parsing URLs, implementing middleware, and serving HTML/CSS/JavaScript files. It includes examples of creating a simple server, handling query strings, and returning JSON data from an API. Each section is structured with input code and expected output, showcasing practical applications of server-side JavaScript.

Uploaded by

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

Web Project

The document provides various examples of Node.js and Express.js code snippets demonstrating functionalities such as displaying messages in the browser, handling HTTP requests, parsing URLs, implementing middleware, and serving HTML/CSS/JavaScript files. It includes examples of creating a simple server, handling query strings, and returning JSON data from an API. Each section is structured with input code and expected output, showcasing practical applications of server-side JavaScript.

Uploaded by

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

1.

Display a message in the browser

Input:
const http = require('http');

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


res.writeHead(200, { 'Content-Type':
'text/html' });

const message = `
<html>
<head>
<title>Node.js Message</title>
</head>
<body style="display: flex; justify-content:
center; align-items: center; height: 100vh;
background-color: #222; color: white; text-align:
center;">
<div>
<h1 style="color: #4CAF50; font-size:
3em;">Hello Everyone</h1>
<p style="font-size: 1.5em;">This is
a message served by a Node.js server.</p>
</div>
</body>
</html>
`;

res.end(message);
});

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

Output:
2.Display the current date and time in the browser.

INPUT:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-
width, initial-scale=1.0">
<title>Live Digital Clock</title>
<style>
body {
background: linear-gradient(45deg,
#ec2654, #e6543a, #3894f0);
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
font-family: Arial, sans-serif;
color: white;
text-align: center;
}
.clock {
font-size: 60px;
font-weight: bold;
background: rgba(0, 0, 0, 0.3);
padding: 20px 40px;
border-radius: 15px;
box-shadow: 0px 0px 15px rgba(0, 0, 0,
0.3);
}
</style>
</head>
<body>
<div class="clock" id="clock">00:00:00</div>

<script>
function updateClock() {
const now = new Date();
let hours =
now.getHours().toString().padStart(2, '0');
let minutes =
now.getMinutes().toString().padStart(2, '0');
let seconds =
now.getSeconds().toString().padStart(2, '0');

document.getElementById('clock').innerText = `$
{hours}:${minutes}:${seconds}`;
}

setInterval(updateClock, 1000);
updateClock(); // Initial call to prevent 1-
second delay
</script>
</body>
</html>

OUTPUT:
3.Pass a query string in URL

INPUT:

const http = require('http');

const url = require('url');

const hostname = 'localhost';

const port = 8356;

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

const parsedUrl = url.parse(req.url, true);

const query = parsedUrl.query;

res.statusCode = 200;

res.setHeader('Content-Type', 'text/html');
if (query.name && query.age) {

res.end(<h1>Hello, ${query.name}!</h1><p>You are ${query.age}


years old.</p>);

} else {

res.end(`<h1>Welcome!</h1><p>Pass a query string like this: <br>

<code>http://localhost:3000/?name=John&age=25</code></p>`);

});

server.listen(port, hostname, () => {

console.log(🚀 Server running at http://${hostname}:${port}/);

});

OUTPUT:

4.Splits up a webpage address into readable parts


INPUT:
const url = require('url');

const webAddress =
'https://example.com:8080/path/to/page?
name=john&age=30#section1';

const parsedUrl = new URL(webAddress);

console.log('Protocol:', parsedUrl.protocol);
console.log('Host:', parsedUrl.host);
console.log('Hostname:', parsedUrl.hostname);
console.log('Port:', parsedUrl.port);
console.log('Pathname:', parsedUrl.pathname);
console.log('Search Params:', parsedUrl.search);
console.log('Hash:', parsedUrl.hash);

const searchParams =
Object.fromEntries(parsedUrl.searchParams.entries());
console.log('Query Parameters:', searchParams);

OUTPUT:

Protocol: https:

Host: example.com:8080

Hostname: example.com

Port: 8080

Pathname: /path/to/page

Search Params: ?name=john&age=30

Hash: #section1

Query Parameters: { name: 'john', age: '30' }

5.Display customized error message


INPUT:
class CustomError extends Error {
constructor(message, statusCode) {
super(message);
this.name = "CustomError";
this.statusCode = statusCode;
}
}

try {
throw new CustomError("User not found", 404);
} catch (error) {
console.error(`Error: ${error.message} (Status
Code: ${error.statusCode})`);
}

OUTPUT:

Error: User not found (Status Code: 404)

6.Event handling

INPUT:
const EventEmitter = require('events');

class OrderProcessor extends EventEmitter {


placeOrder(orderId, customerName) {
console.log(`📦 Order placed: ${orderId} by $
{customerName}`);
this.emit('orderReceived', orderId);
}
}

const orderProcessor = new OrderProcessor();

orderProcessor.on('orderReceived', (orderId) => {


console.log(`🔄 Processing order: ${orderId}...`);
setTimeout(() => {
console.log(`✅ Order ${orderId} is completed!
`);
}, 2000);
});

orderProcessor.placeOrder(101, "Alice");

OUTPUT:

📦 Order placed: 101 by Alice

🔄 Processing order: 101...

✅ Order 101 is completed!


EXPRESS.JS
1.Implementation of 2 middle wares

INPUT:
const express = require('express');
const bodyParser = require('body-parser');
const path = require('path');
const app = express();
const port = 3000;

const requestLogger = (req, res, next) => {


console.log(`${req.method} ${req.url} - ${new
Date().toISOString()}`);
next();
};

const authMiddleware = (req, res, next) => {


const token = req.headers['authorization'];
if (token === 'secret-token') {
next();
} else {
res.status(403).json({ message: 'Forbidden: Invalid Token' });
}
};

app.use(bodyParser.json());
app.use(requestLogger);
app.use(authMiddleware);

const apiRouter = express.Router();

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


res.status(200).json({ message: 'GET request received', data: [1,
2, 3] });
});

apiRouter.post('/data', (req, res) => {


res.status(201).json({ message: 'POST request received',
receivedData: req.body });
});
apiRouter.put('/data/:id', (req, res) => {
res.status(200).json({ message: `PUT request received for ID $
{req.params.id}`, updatedData: req.body });
});

apiRouter.delete('/data/:id', (req, res) => {


res.status(204).send();
});

app.use('/api', apiRouter);

app.use(express.static(path.join(__dirname, 'public')));

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


res.sendFile(path.join(__dirname, 'public', 'index.html'));
});

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

OUTPUT:

GET / - 2025-03-03T12:03:40.136Z

GET /favicon.ico - 2025-03-03T12:03:40.316Z

2.Filtering paths using URL prefix.

INPUT:
const express = require('express');
const app = express();
const PORT = 3000;

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


if (req.path.startsWith('/api')) {
return next();
}
res.status(403).send('Forbidden: Access restricted to API routes');
});

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


res.json({ message: 'User list' });
});

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


res.json({ message: 'Product list' });
});

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

OUTPUT:

3.Setting the status code.

Input:
const express = require('express');
const app = express();

// API route that returns JSON with a status code


app.get('/api/message', (req, res) => {
res.status(200).json({ message: "Hello, this is an Express
API!" });
});

// Start the server


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

OUTPUT:
{"message":"Hello, this is an Express
API!"}

4.Parsing data from request.


INPUT:
const express = require('express');
const app = express();
const PORT = 3000;

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


res.send('Welcome to my Express.js App!');
});

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

OUTPUT:

5.Demonstrating GET,POST,PUT and DELETE requests.

INPUT:
const express = require('express');
const app = express();
const PORT = 3000;

app.use(express.json());

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


res.send('Hello, welcome to my Express server!');
});

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


res.json({ message: 'You sent:', data: req.body });
});

app.listen(PORT, () => console.log(`🚀 Server running on


http://localhost:${PORT}`));

OUTPUT:
6. Using middleware to log request details.

INPUT:
const express = require('express');
const app = express();

const requestLogger = (req, res, next) => {


const timeStamp = new Date().toISOString();
console.log(`[${timeStamp}] ${req.method} ${req.url}`);
next(); // Pass control to the next middleware
};

app.use(requestLogger);

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


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

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


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

const PORT = 3000;


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

OUTPUT:

7.Serving HTML,CSS AND JAVSCRIPT files.

INPUT:
const express = require('express');

const app = express();

// Route to serve the HTML page

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

res.send(`

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-


scale=1.0">

<title>Express Inline Page</title>

<style>

body {

font-family: Arial, sans-serif;

text-align: center;

background-color: #f0f0f0;

padding: 50px;

h1 {

color: #333;

button {
background-color: #007bff;

color: white;

border: none;

padding: 10px 20px;

font-size: 16px;

cursor: pointer;

border-radius: 5px;

button:hover {

background-color: #0056b3;

</style>

</head>

<body>

<h1>Welcome to Express Inline Page</h1>

<button onclick="showMessage()">Click Me</button>

<script>

function showMessage() {

alert("Hello from Express!");

</script>

</body>

</html>
`);

});

// Start the server

const PORT = 3000;

app.listen(PORT, () => {

console.log(`Server is running on http://localhost:${PORT}`);

});

OUTPUT:

8.Returning JSON data from an API.

INPUT:
const express = require('express');
const app = express();

const users = [
{ id: 1, name: "Alice", email: "[email protected]" },
{ id: 2, name: "Bob", email: "[email protected]" },
{ id: 3, name: "Charlie", email: "[email protected]" }
];

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


res.json(users);
});

const PORT = 5000;


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

OUTPUT:

[{"id":1,"name":"Alice","email":"[email protected]"},

{"id":2,"name":"Bob","email":"[email protected]"},

{"id":3,"name":"Charlie","email":"[email protected]"}]

You might also like