[go: up one dir, main page]

0% found this document useful (0 votes)
9 views6 pages

Express Assignment Solutions

The document provides multiple examples of Express applications, including a simple 'Hello World' app, an app with protected routes using authentication middleware, a RESTful API for task management with CRUD operations, error handling middleware, an email-sending app using Nodemailer, and a calculator API for basic arithmetic operations. Each example includes the necessary code and demonstrates different functionalities of Express.js. All applications are set to run on port 3000.

Uploaded by

bhavyamathur2022
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)
9 views6 pages

Express Assignment Solutions

The document provides multiple examples of Express applications, including a simple 'Hello World' app, an app with protected routes using authentication middleware, a RESTful API for task management with CRUD operations, error handling middleware, an email-sending app using Nodemailer, and a calculator API for basic arithmetic operations. Each example includes the necessary code and demonstrates different functionalities of Express.js. All applications are set to run on port 3000.

Uploaded by

bhavyamathur2022
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/ 6

ASMITA SARKAR

Express Assignment Solutions


1. Hello World Express Application

Create a simple Express app that listens on port 3000 and responds with "Hello, Students!" when
accessed.

const express = require('express');


const app = express();

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


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

app.listen(3000, () => {
console.log('Server is running on port 3000');
});

2. Express App with Protected Routes (Authentication Middleware)

This example uses a simple middleware to protect routes. In a real-world scenario, replace the
authentication logic with proper checks (like JWT or session validation).

const express = require('express');


const app = express();

// Simple authentication middleware


function authMiddleware(req, res, next) {
const auth = req.headers.authorization;
if (auth === 'Bearer secrettoken') {
next();
} else {
res.status(401).send('Unauthorized');
}
}

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


res.send('Public Route');
});

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


res.send('Protected Route');
});

app.listen(3000, () => {
console.log('Server running on port 3000');
});

3. RESTful API for Task Management (CRUD Operations)

A basic REST API to manage tasks (in-memory array for demonstration):

const express = require('express');


const app = express();

app.use(express.json());

let tasks = [];


let id = 1;

// Create Task
app.post('/tasks', (req, res) => {
const task = { id: id++, ...req.body };
tasks.push(task);
res.status(201).json(task);
});

// Read All Tasks


app.get('/tasks', (req, res) => {
res.json(tasks);
});

// Read Task by ID
app.get('/tasks/:id', (req, res) => {
const task = tasks.find(t => t.id == req.params.id);
if (task) res.json(task);
else res.status(404).send('Task not found');
});

// Update Task
app.put('/tasks/:id', (req, res) => {
const task = tasks.find(t => t.id == req.params.id);
if (task) {
Object.assign(task, req.body);
res.json(task);
} else {
res.status(404).send('Task not found');
}
});

// Delete Task
app.delete('/tasks/:id', (req, res) => {
const index = tasks.findIndex(t => t.id == req.params.id);
if (index !== -1) {
tasks.splice(index, 1);
res.sendStatus(204);
} else {
res.status(404).send('Task not found');
}
});

app.listen(3000, () => {
console.log('Task API running on port 3000');
});

4. Express App with Error Handling Middleware

Demonstrates how to handle and log errors in Express.

const express = require('express');


const app = express();

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


throw new Error('Something went wrong!');
});
// Error handling middleware
app.use((err, req, res, next) => {
console.error(err.stack); // Log error
res.status(500).send('Internal Server Error');
});

app.listen(3000, () => {
console.log('Server running on port 3000');
});

5. Express App Sending Emails with Nodemailer

Install Nodemailer:

npm install nodemailer

Example code:

const express = require('express');


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

app.use(express.json());

const transporter = nodemailer.createTransport({


service: 'gmail',
auth: {
user: 'your.email@gmail.com',
pass: 'yourpassword'
}
});

app.post('/send-email', (req, res) => {


const { to, subject, text } = req.body;
const mailOptions = {
from: 'your.email@gmail.com',
to,
subject,
text
};

transporter.sendMail(mailOptions, (error, info) => {


if (error) {
return res.status(500).send(error.toString());
}
res.send('Email sent: ' + info.response);
});
});

app.listen(3000, () => {
console.log('Email app running on port 3000');
});

6. Express Calculator API (Addition, Subtraction, Multiplication, Division)

const express = require('express');


const app = express();

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


const { a, b } = req.query;
res.send(`Result: ${Number(a) + Number(b)}`);
});

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


const { a, b } = req.query;
res.send(`Result: ${Number(a) - Number(b)}`);
});

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


const { a, b } = req.query;
res.send(`Result: ${Number(a) * Number(b)}`);
});

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


const { a, b } = req.query;
if (Number(b) === 0) {
res.status(400).send('Cannot divide by zero');
} else {
res.send(`Result: ${Number(a) / Number(b)}`);
}
});

app.listen(3000, () => {
console.log('Calculator API running on port 3000');
});

You might also like