Backend 2.3

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 3

EXPERIMENT:- 2.

Student Name: Shubham saini UID:22MCA20830


Branch: MCA Section/Group 22MCA-3(B)
Semester: 3rd Date of Performance: 2/11/2023
Subject Name:BACKEND TECHNOLOGY Subject Code:22CAP-706

Aim
Write the code that show use of API

index.js
HTML CODE:-
constCODE:-
HTML express = require('express');
const express = require("express");
const bodyParser = require('body-parser');
<!DOCTYPE const html> = require("body-parser");
bodyParser
var
!DOCTYPE
<!DOCTYPE mongoose
<html
html>
html>
lang="en"> = require('mongoose');
<html lang="en"> = require("./routes/user");
const user
<htmlmongoose.connect('mongodb://127.0.0.1:27017/MCA');
lang="en">
<head> const InitiateMongoServer = require("./config/db");
const/* app =nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt
express();
<head> * Clickcharset="UTF-8"
<head> <meta /> to change this license
app.use(bodyParser.urlencoded({
<meta
<meta <meta // name="viewport"
Initiate
charset="UTF-8"
*charset="UTF-8">
Click Mongo /> Server extended: false }));
content="width=device-width,
nbfs://nbhost/SystemFileSystem/Templates/JSP_Servlet/Servlet.java initial-scale=1.0" /> this template
to edit
app.use(express.static(__dirname));
<meta
<meta
Merge */
sortname="viewport"
<title>Employ
InitiateMongoServer();
http-equiv="X-UA-Compatible" content="width=device-width,
is a sorting Salary</title>
algorithm that works by dividing aninitial-scale=1.0"
content="IE=edge"> array into smaller/>subarrays, sorting each
//
<meta Connect
<title>Multi-page
subarray,<link to MongoDB
name="viewport"
then Responsive
andrel="stylesheet"
merging Facebook Clone</title>
thehref="./tableNode.css">
content="width=device-width,
sorted subarrays initial-scale=1.0">
back together to form the final sorted array. .
var db
<title>Currency
import
</head> = mongoose.connection;
const java.io.IOException;
appConverter</title>
= express();
<!-- Facebook Favicon -->
db.on('error',
<link import
ALGORITHM:- rel="stylesheet"
<body>
<link console.error.bind(console,
java.io.PrintWriter;
rel="icon" />'connection error:'));
href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
href="/images/favicon.png"
db.once('open',
<scriptimport
<div function () {
src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js">
jakarta.servlet.ServletException;
//class="container">
PORT
</script>
import jakarta.servlet.annotation.WebServlet;
console.log("Connection
<!--1:
step
<script <div const
Fontawesome
start
import PORT Icons= --> Successful!");
class="header"><h1>Employ
process.env.PORT Salary Data</h1></div>
||4200;
src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js">
jakarta.servlet.http.HttpServlet;
});
<script
</script> <div
import src="https://kit.fontawesome.com/7433d3320f.js"
class="main">
jakarta.servlet.http.HttpServletRequest; crossorigin="anonymous"></script>
var
step
<script student
2: Declare
<div
import // File = mongoose.Schema({
array and
class="table">
Middleware
left, right, mid variable
src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js">
jakarta.servlet.http.HttpServletResponse;
UID:
<!--
</script> CSS
import String,
<table
-->
jakarta.servlet.http.HttpSession;
border="solid">
app.use(bodyParser.json());
<link
step rel="stylesheet"
3: perform href="styles.css" />
Name:
</head> <tr>String, function.
merge
<link
if Course1:
left
/**
> right String,(req,
rel="preconnect"
<th>S.No</th>
app.get("/",
href="https://fonts.gstatic.com">
res) => {
<link *href="https://fonts.googleapis.com/css2?family=Amiri&family=Lobster&family=Pacifico&display=swap"
Course2:
<body>
rel="stylesheet">
* @author String,
<th>Employee_Id</th>
res.json({ message: "API Working" });
Shubham
returnCourse3:
<!-- Navigation
*/ }); String
Section -->
<th>Employ_Name</th>
});
<nav>
<th>Position</th>
@WebServlet(urlPatterns = {"/httpsession"})
const
mid= <!--
<link student_model
Left Section
(left+right)/2
public
rel="stylesheet"
class -->
httpsession
<th>Salary</th> = mongoose.model('student_model',
href="styles.css">
extends HttpServlet { student, 'Students');
<div class="nav-left">
var
</head> Course = mongoose.Schema({
</tr> left, mid) user);src="images/logo.png" class="logo" /></a>
app.use("/user",
<a href="index.html"><img
mergesort(array,
CID: /** String,
<body> *<!--
<ul> 1st entry
Processes --> for both HTTP <code>GET</code> and <code>POST</code>
requests
Course_Name:
<li><img
mergesort(array, <tr>
*app.listen(PORT, String,
right)(req, res) => { /></li>
src="images/notification.png"
methods.mid+1,
Credits:
<li><img Number
src="images/inbox.png"
<td>1</td>
* console.log(`Server
<h1 class="heading text-centerStarted
display-2">/></li>
at PORT ${PORT}`);
}); <li><img
merge(array,
Currency src="images/video.png"
left, mid,
<td>111</td>
*});@param
Converter</h1>right)
request servlet request/></li>
const
<hr> </ul> course_model
* @param response
<td>Shubham</td> = mongoose.model('course_model',
servlet response Course, 'Courses');
step </div>
4:class="container">
Stop
app.get('/',
<div * @throws(req,
<td>CEO</td> res) => {
ServletException if a servlet-specific error occurs
res.sendFile(__dirname
* @throws IOException + '/home.html');
if an I/O error occurs
*/ <td id="ceo"></td>
<div class="main">
}); </tr>
app.get('/add_student',
Sign up:- (req, res) => {
res.sendFile(__dirname
<tr> + '/add_student.html');
}); <td>2</td>
<td>222</td>(req, res) => {
app.get('/add_course',
<td>Sumit</td>
res.sendFile(__dirname
<td>COO</td> + '/add_course.html');
}); <td id="coo"></td>
app.get('/students',
</tr> async (req, res) => {
try { <!-- 3rd entry -->
const<tr> students = await student_model.find({});
<td>3</td>
res.json(students);
<td>333</td>
} catch (error) {
<td>Shivam</td>
console.log('An errorHead</td>
<td>Operations occurred while fetching the data:', error);
res.status(500).send('An
<td id="oh"></td> error occurred while fetching the data.');
} </tr>
}); </table>
<button style="color:white; background-color:blue">Show Salary</button>
app.post('/add_student',
</div> async (req, res) => {
Logintry:-{ </div>
const
</div> newData = new student_model({
UID: req.body.id,
<script>
Name: req.body.name,
function showSalary(){
Course1: req.body.sub1,
document.getElementById('ceo').innerText="100000";
Course2: req.body.sub2,
document.getElementById('coo').innerText="200000";
Course3: req.body.sub3
document.getElementById('oh').innerText="100";
}});
awaitbtn=document.querySelector("button");
const newData.save();
console.log('Student Added');
btn.addEventListener('click',showSalary);
return res.redirect('home.html');
</script>
} catch
</body> (error) {
console.log('An error occurred while saving the data.');
</html>
}
}); by me:-
Verify
app.post('/add_course',
NODE.js Code async (req, res) => {
try {
const
var newData = new course_model({
http=require('http');
CID: req.body.id,
varCourse_Name:
fs=require('fs'); req.body.name,
Credits: req.body.credits,
http.createServer(function(req,res){
});
fs.readFile('data.html',function(err,data){
await newData.save();
if (err) {
console.log("Course Added");
res.writeHead(404, {'Content-type': 'text/plain'});
return res.redirect('home.html');
res.write('File not found');
} catch
} else(error)
{ {
console.log('An error{'Content-type':
res.writeHead(200, occurred while saving the data.');
'text/html'});
} res.write(data);
}); }res.end();
app.post('/search',
}); async (req, res) => {
const { id } = req.body;
}).listen(8080);
try {node
const student = await student_model.findOne({ UID: id });
const subject1 = await course_model.findOne({ CID: student.Course1 });
const subject2 = await course_model.findOne({ CID: student.Course2 });
const subject3 = await course_model.findOne({ CID: student.Course3 });
OUTPUT
const total = (subject1 ? subject1.Credits : 0)
+ (subject2 ? subject2.Credits : 0)
+ (subject3 ? subject3.Credits : 0);
if (student) {
return res.send(`
<link rel="stylesheet"
href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
<div class="container mt-5">
<h1 class="text-center">Search Result</h1>
<div class="card mt-5">
<div class="card-body">
<h5 class="card-title">${student.Name}</h5>
<p class="card-text">UID: ${student.UID}</p>
<p class="card-text"><b>Course Code:${subject1 ? subject1.CID : 'N/A'} </b>
&nbsp&nbsp&nbsp
<b>Course Name:${subject1 ? subject1.Course_Name : 'N/A'}</b> &nbsp&nbsp&nbsp
(${subject1 ? subject1.Credits : 'N/A'} credits)</p>
<p class="card-text"><b>Course Code:${subject2 ? subject2.CID : 'N/A'} </b>
&nbsp&nbsp&nbsp
<b>Course Name:${subject2 ? subject2.Course_Name : 'N/A'}</b> &nbsp&nbsp&nbsp
(${subject2 ? subject2.Credits : 'N/A'} credits)</p>
<p class="card-text"><b>Course Code:${subject3 ? subject3.CID : 'N/A'} </b>
&nbsp&nbsp&nbsp
<b>Course Name:${subject3 ? subject3.Course_Name : 'N/A'}</b> &nbsp&nbsp&nbsp
(${subject3 ? subject3.Credits : 'N/A'} credits)</p>
<p class="card-text">Total Credits: ${total}</p>
</div>
</div>
</div> outcomes (What I have learnt):
Learning
`);
1.} I learned to update data in mongodb.
2.else
I learned
{ to insert and manage data of a collection in mongodb.
3. Ireturn
learnt res.send('No
to operate CRUD operations
Student found');
}
}
catch (err) {
console.error(err);
}
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});

You might also like