long

Long 1.Create an HTML form that contain the Student Registration details and write a

JavaScript to validate Student first and last name as it should not contain other than

alphabets and age should be between 18 to 50.


<!DOCTYPE html>

<html>

<head>

    <title>Student Registration Form</title>

    <script>

        function validateForm() {

            var firstName = document.forms["registration"]["firstName"].value;

            var lastName = document.forms["registration"]["lastName"].value;

            var age = document.forms["registration"]["age"].value;


            var namePattern = /^[A-Za-z]+$/;


            if (!namePattern.test(firstName)) {

                alert("First name must contain only alphabets.");

                return false;

            }


            if (!namePattern.test(lastName)) {

                alert("Last name must contain only alphabets.");

                return false;

            }


            if (age < 18 || age > 50) {

                alert("Age must be between 18 and 50.");

                return false;

            }

            

            return true;

        }

    </script>

</head>

<body>

    <h2>Student Registration Form</h2>

    <form name="registration" onsubmit="return validateForm()">

        <label for="firstName">First Name:</label><br>

        <input type="text" id="firstName" name="firstName"><br><br>

        

        <label for="lastName">Last Name:</label><br>

        <input type="text" id="lastName" name="lastName"><br><br>

        

        <label for="age">Age:</label><br>

        <input type="number" id="age" name="age"><br><br>

        

        <input type="submit" value="Register">

    </form>

</body>

</html>

Long 2.Create an HTML form that contain the Employee Registration details and write

a JavaScript to validate DOB, Joining Date, and Salary.


<!DOCTYPE html>

<html>

<head>

    <title>Employee Registration Form</title>

    <script>

        function validateForm() {

            var dob = document.forms["registration"]["dob"].value;

            var joiningDate = document.forms["registration"]["joiningDate"].value;

            var salary = document.forms["registration"]["salary"].value;


            if (!isValidDate(dob)) {

                alert("Please enter a valid Date of Birth.");

                return false;

            }


            if (!isValidDate(joiningDate)) {

                alert("Please enter a valid Joining Date.");

                return false;

            }


            if (salary <= 0) {

                alert("Salary must be greater than zero.");

                return false;

            }


            return true;

        }


        function isValidDate(dateString) {

            var datePattern = /^\d{4}-\d{2}-\d{2}$/; // YYYY-MM-DD format

            if (!datePattern.test(dateString)) {

                return false;

            }

            var date = new Date(dateString);

            var now = new Date();

            if (date > now) {

                return false;

            }

            return true;

        }

    </script>

</head>

<body>

    <h2>Employee Registration Form</h2>

    <form name="registration" onsubmit="return validateForm()">

        <label for="firstName">First Name:</label><br>

        <input type="text" id="firstName" name="firstName"><br><br>


        <label for="lastName">Last Name:</label><br>

        <input type="text" id="lastName" name="lastName"><br><br>


        <label for="dob">Date of Birth:</label><br>

        <input type="date" id="dob" name="dob"><br><br>


        <label for="joiningDate">Joining Date:</label><br>

        <input type="date" id="joiningDate" name="joiningDate"><br><br>


        <label for="salary">Salary:</label><br>

        <input type="number" id="salary" name="salary"><br><br>


        <input type="submit" value="Register">

    </form>

</body>

</html>

Long 3.Create an HTML form for Login and write a JavaScript to validate email ID

using Regular Expression



<!DOCTYPE html>

<html>

<head>

    <title>Login Form</title>

    <script>

        function validateForm() {

            var email = document.forms["login"]["email"].value;

            var emailPattern = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;


            if (!emailPattern.test(email)) {

                alert("Please enter a valid email address.");

                return false;

            }


            return true;

        }

    </script>

</head>

<body>

    <h2>Login Form</h2>

    <form name="login" onsubmit="return validateForm()">

        <label for="email">Email ID:</label><br>

        <input type="text" id="email" name="email"><br><br>


        <label for="password">Password:</label><br>

        <input type="password" id="password" name="password"><br><br>


        <input type="submit" value="Login">

    </form>

</body>

</html>


Long 4.Create a Node.js file that writes an HTML form, with an upload field.

// Create an HTTP server

const http = require('http');


// Create the server

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

  // Set the response header

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


  // Create the HTML form

  const form = `

    <html>

      <body>

        <h1>Upload File</h1>

        <form action="/upload" method="post" enctype="multipart/form-data">

          <input type="file" name="file" />

          <button type="submit">Upload</button>

        </form>

      </body>

    </html>

  `; // Make sure this backtick is included


  // Send the HTML form as the response

  res.end(form);

}).listen(3000, () => {

  console.log('Server started on port 3000');

});

Long 5.Create a node.js file that Select all records from the "customers" table, and display

the result object on console.


*customers.js*

npm install mysqlconst mysql = require('mysql');


// Create a connection to the database

const db = mysql.createConnection({

  host: 'your_host',

  user: 'your_username',

  password: 'your_password',

  database: 'your_database'

});


// Connect to the database

db.connect((err) => {

  if (err) {

    console.error('Error connecting to the database:', err);

    return;

  }

  console.log('Connected to the database');


  // Select all records from the "customers" table

  const query = 'SELECT * FROM customers';

  db.query(query, (err, results) => {

    if (err) {

      console.error('Error running query:', err);

      return;

    }

    console.log('Results:');

    console.log(results);

  });

});

Long 6.Create a node.js file that Insert Multiple Records in "student" table, and display the

result object on console.


*insert_students.js

npm install mysql

const mysql = require('mysql');


// Create a connection to the database

const db = mysql.createConnection({

  host: 'your_host',

  user: 'your_username',

  password: 'your_password',

  database: 'your_database'

});


// Connect to the database

db.connect((err) => {

  if (err) {

    console.error('Error connecting to the database:', err);

    return;

  }

  console.log('Connected to the database');


  // Insert multiple records into the "student" table

  const students = [

    { name: 'John Doe', age: 20, grade: 'A' },

    { name: 'Jane Doe', age: 22, grade: 'B' },

    { name: 'Bob Smith', age: 21, grade: 'C' }

  ];


  const query = 'INSERT INTO student (name, age, grade) VALUES ?';

  const values = students.map((student) => [student.name, student.age, student.grade]);


  db.query(query, [values], (err, results) => {

    if (err) {

      console.error('Error running query:', err);

      return;

    }

    console.log('Results:');

    console.log(results);

  });

});

Long 7.Create a node.js file that Select all records from the "customers" table, and delete the

specified record


*delete_customer.js*

npm install mysql

const mysql = require('mysql');


// Create a connection to the database

const db = mysql.createConnection({

  host: 'your_host',

  user: 'your_username',

  password: 'your_password',

  database: 'your_database'

});


// Connect to the database

db.connect((err) => {

  if (err) {

    console.error('Error connecting to the database:', err);

    return;

  }

  console.log('Connected to the database');


  // Select all records from the "customers" table

  const query = 'SELECT * FROM customers';

  db.query(query, (err, results) => {

    if (err) {

      console.error('Error running query:', err);

      return;

    }

    console.log('Results:');

    console.log(results);


    // Delete a specified record

    const customerIdToDelete = 1; // Replace with the ID of the customer to delete

    const deleteQuery = 'DELETE FROM customers WHERE id = ?';

    db.query(deleteQuery, customerIdToDelete, (err, results) => {

      if (err) {

        console.error('Error running query:', err);

        return;

      }

      console.log(Deleted customer with ID ${customerIdToDelete});

    });

  });

});

Long 8.Creat a node js express server to provide login REST API validate response on any REST 

client like POSTMAN


*server.js*

npm install express mysql

const express = require('express');

const mysql = require('mysql');

const bodyParser = require('body-parser');


const app = express();


// Create a connection to the database

const db = mysql.createConnection({

  host: 'your_host',

  user: 'your_username',

  password: 'your_password',

  database: 'your_database'

});


// Connect to the database

db.connect((err) => {

  if (err) {

    console.error('Error connecting to the database:', err);

    return;

  }

  console.log('Connected to the database');

});


// Use body-parser to parse JSON requests

app.use(bodyParser.json());


// Define the login API endpoint

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

  const { username, password } = req.body;


  // Validate the request

  if (!username || !password) {

    return res.status(400).json({ error: 'Username and password are required' });

  }


  // Query the database to validate the user

  const query = 'SELECT * FROM users WHERE username = ? AND password = ?';

  db.query(query, [username, password], (err, results) => {

    if (err) {

      return res.status(500).json({ error: 'Error validating user' });

    }


    if (results.length === 0) {

      return res.status(401).json({ error: 'Invalid username or password' });

    }


    // Return a success response with a JSON Web Token (JWT)

    const user = results[0];

    const token = generateToken(user);

    res.json({ token });

  });

});


// Generate a JSON Web Token (JWT) for the user

function generateToken(user) {

  const payload = { userId: user.id, username: user.username };

  const secret = 'your_secret_key';

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

  return token;

}


// Start the server

const port = 3000;

app.listen(port, () => {

  console.log(Server started on port ${port});

});

Long 9.Create a node js express server to provide register REST API validate response on any REST 

client like POSTMAN


*server.js*

npm install express mysql

const express = require('express');

const mysql = require('mysql');

const bodyParser = require('body-parser');

const bcrypt = require('bcrypt');


const app = express();


// Create a connection to the database

const db = mysql.createConnection({

  host: 'your_host',

  user: 'your_username',

  password: 'your_password',

  database: 'your_database'

});


// Connect to the database

db.connect((err) => {

  if (err) {

    console.error('Error connecting to the database:', err);

    return;

  }

  console.log('Connected to the database');

});


// Use body-parser to parse JSON requests

app.use(bodyParser.json());


// Define the register API endpoint

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

  const { username, email, password } = req.body;


  // Validate the request

  if (!username || !email || !password) {

    return res.status(400).json({ error: 'Username, email, and password are required' });

  }


  // Hash the password using bcrypt

  bcrypt.hash(password, 10, (err, hash) => {

    if (err) {

      return res.status(500).json({ error: 'Error hashing password' });

    }


    // Insert the user into the database

    const query = 'INSERT INTO users (username, email, password) VALUES (?, ?, ?)';

    db.query(query, [username, email, hash], (err, results) => {

      if (err) {

        return res.status(500).json({ error: 'Error inserting user into database' });

      }


      // Return a success response with a JSON Web Token (JWT)

      const user = { id: results.insertId, username, email };

      const token = generateToken(user);

      res.json({ token });

    });

  });

});


// Generate a JSON Web Token (JWT) for the user

function generateToken(user) {

  const payload = { userId: user.id, username: user.username };

  const secret = 'your_secret_key';

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

  return token;

}


// Start the server

const port = 3000;

app.listen(port, () => {

  console.log(Server started on port ${port});

});

Long 10.Create a nodejs express server to list all the employees from the employee table validate 

response on any REST client like POSTMAN


*server.js*

npm install express mysql

const express = require('express');

const mysql = require('mysql');


const app = express();


// Create a connection to the database

const db = mysql.createConnection({

  host: 'your_host',

  user: 'your_username',

  password: 'your_password',

  database: 'your_database'

});


// Connect to the database

db.connect((err) => {

  if (err) {

    console.error('Error connecting to the database:', err);

    return;

  }

  console.log('Connected to the database');

});


// Define the API endpoint to list all employees

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

  const query = 'SELECT * FROM employee';

  db.query(query, (err, results) => {

    if (err) {

      return res.status(500).json({ error: 'Error fetching employees' });

    }


    // Return a success response with the list of employees

    res.json(results);

  });

});


// Start the server

const port = 3000;

app.listen(port, () => {

  console.log(Server started on port ${port});

});

long 11.Build a simple multi-page React application using React Router. Create different routes for 

a home page, about page, and contact page. Implement navigation between these routes.


npx create-react-app react-router-app

npm install react-router-dom

import React from 'react';

import ReactDOM from 'react-dom';

import { BrowserRouter, Route, Switch } from 'react-router-dom';

import App from './App';


ReactDOM.render(

  <BrowserRouter>

    <App />

  </BrowserRouter>,

  document.getElementById('root')

);

import React from 'react';

import { Link, Route, Switch } from 'react-router-dom';

import HomePage from './HomePage';

import AboutPage from './AboutPage';

import ContactPage from './ContactPage';


function App() {

  return (

    <div>

      <nav>

        <ul>

          <li><Link to="/">Home</Link></li>

          <li><Link to="/about">About</Link></li>

          <li><Link to="/contact">Contact</Link></li>

        </ul>

      </nav>

      <Switch>

        <Route path="/" exact component={HomePage} />

        <Route path="/about" component={AboutPage} />

        <Route path="/contact" component={ContactPage} />

      </Switch>

    </div>

  );

}


export default App;

import React from 'react';


function HomePage() {

  return (

    <div>

      <h1>Home Page</h1>

      <p>Welcome to the home page!</p>

    </div>

  );

}


export default HomePage;

import React from 'react';


function AboutPage() {

  return (

    <div>

      <h1>About Page</h1>

      <p>This is the about page.</p>

    </div>

  );

}


export default AboutPage;


import React from 'react';


function ContactPage() {

  return (

    <div>

      <h1>Contact Page</h1>

      <p>This is the contact page.</p>

    </div>

  );

}


export default ContactPage;

import React from 'react';


function ContactPage() {

  return (

    <div>

      <h1>Contact Page</h1>

      <p>This is the contact page.</p>

    </div>

  );

}


export default ContactPage;

Long 12.Create a nodejs express server to insert employee into database.


*server.js*

npm install express mysql

const express = require('express');

const mysql = require('mysql');

const bodyParser = require('body-parser');


const app = express();


// Create a connection to the database

const db = mysql.createConnection({

  host: 'your_host',

  user: 'your_username',

  password: 'your_password',

  database: 'your_database'

});


// Connect to the database

db.connect((err) => {

  if (err) {

    console.error('Error connecting to the database:', err);

    return;

  }

  console.log('Connected to the database');

});


// Parse JSON bodies

app.use(bodyParser.json());


// Define the API endpoint to insert an employee

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

  const { name, department, salary } = req.body;

  const query = 'INSERT INTO employee (name, department, salary) VALUES (?, ?, ?)';

  db.query(query, [name, department, salary], (err, results) => {

    if (err) {

      return res.status(500).json({ error: 'Error inserting employee' });

    }


    // Return a success response with the inserted employee's ID

    res.json({ id: results.insertId });

  });

});


// Start the server

const port = 3000;

app.listen(port, () => {

  console.log(Server started on port ${port});

});

Long 13.Create a nodejs express server to search an employee by email validate response on any 

REST client like POSTMAN


*server.js*

npm install express mysql body-parser

const express = require('express');

const mysql = require('mysql');

const bodyParser = require('body-parser');


const app = express();


// Create a connection to the database

const db = mysql.createConnection({

  host: 'your_host',

  user: 'your_username',

  password: 'your_password',

  database: 'your_database'

});


// Connect to the database

db.connect((err) => {

  if (err) {

    console.error('Error connecting to the database:', err);

    return;

  }

  console.log('Connected to the database');

});


// Parse JSON bodies

app.use(bodyParser.json());


// Define the API endpoint to search an employee by email

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

  const email = req.query.email;

  const query = 'SELECT * FROM employee WHERE email = ?';

  db.query(query, [email], (err, results) => {

    if (err) {

      return res.status(500).json({ error: 'Error searching employee' });

    }


    // Return the search result

    if (results.length === 0) {

      res.status(404).json({ error: 'Employee not found' });

    } else {

      res.json(results[0]);

    }

  });

});


// Start the server

const port = 3000;

app.listen(port, () => {

  console.log(Server started on port ${port});

});

Long 14.Create a nodejs express server to generate jwt token in the response of login api.


*server.js*

npm install express mysql body-parser jsonwebtoken

const express = require('express');

const mysql = require('mysql');

const bodyParser = require('body-parser');

const jwt = require('jsonwebtoken');


const app = express();


// Create a connection to the database

const db = mysql.createConnection({

  host: 'your_host',

  user: 'your_username',

  password: 'your_password',

  database: 'your_database'

});


// Connect to the database

db.connect((err) => {

  if (err) {

    console.error('Error connecting to the database:', err);

    return;

  }

  console.log('Connected to the database');

});


// Parse JSON bodies

app.use(bodyParser.json());


// Define a secret key for JWT token generation

const secretKey = 'your_secret_key';


// Define the API endpoint to login and generate a JWT token

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

  const { email, password } = req.body;

  const query = 'SELECT * FROM employee WHERE email = ? AND password = ?';

  db.query(query, [email, password], (err, results) => {

    if (err) {

      return res.status(500).json({ error: 'Error logging in' });

    }


    if (results.length === 0) {

      return res.status(401).json({ error: 'Invalid email or password' });

    }


    const employee = results[0];

    const token = jwt.sign({ id: employee.id, email: employee.email }, secretKey, {

      expiresIn: '1h'

    });


    res.json({ token });

  });

});


// Start the server

const port = 3000;

app.listen(port, () => {

  console.log(Server started on port ${port});

});

Long 15.Create a nodejs server to insert teacher data into teacher table use mysql.


*server.js*

npm install express mysql body-parser

const express = require('express');

const mysql = require('mysql');

const bodyParser = require('body-parser');


const app = express();


// Create a connection to the database

const db = mysql.createConnection({

  host: 'your_host',

  user: 'your_username',

  password: 'your_password',

  database: 'your_database'

});


// Connect to the database

db.connect((err) => {

  if (err) {

    console.error('Error connecting to the database:', err);

    return;

  }

  console.log('Connected to the database');

});


// Parse JSON bodies

app.use(bodyParser.json());


// Define the API endpoint to insert a teacher

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

  const { name, department, email } = req.body;

  const query = 'INSERT INTO teacher (name, department, email) VALUES (?, ?, ?)';

  db.query(query, [name, department, email], (err, results) => {

    if (err) {

      return res.status(500).json({ error: 'Error inserting teacher' });

    }


    // Return a success response with the inserted teacher's ID

    res.json({ id: results.insertId });

  });

});


// Start the server

const port = 3000;

app.listen(port, () => {

  console.log(Server started on port ${port});

});

Long 16Create a node js server to delete student record by roll no using mysql.


*server.js*

npm install express mysql body-parser

const express = require('express');

const mysql = require('mysql');

const bodyParser = require('body-parser');


const app = express();


// Create a connection to the database

const db = mysql.createConnection({

  host: 'your_host',

  user: 'your_username',

  password: 'your_password',

  database: 'your_database'

});


// Connect to the database

db.connect((err) => {

  if (err) {

    console.error('Error connecting to the database:', err);

    return;

  }

  console.log('Connected to the database');

});


// Parse JSON bodies

app.use(bodyParser.json());


// Define the API endpoint to delete a student by roll number

app.delete('/api/students/:rollNo', (req, res) => {

  const rollNo = req.params.rollNo;

  const query = 'DELETE FROM student WHERE roll_no = ?';

  db.query(query, [rollNo], (err, results) => {

    if (err) {

      return res.status(500).json({ error: 'Error deleting student' });

    }


    if (results.affectedRows === 0) {

      return res.status(404).json({ error: 'Student not found' });

    }


    res.json({ message: 'Student deleted successfully' });

  });

});


// Start the server

const port = 3000;

app.listen(port, () => {

  console.log(Server started on port ${port});

});

Long 17.Create a node js server to list all the students having marks greater than 60 using mysql.


*server.js*

npm install express mysql body-parser

const express = require('express');

const mysql = require('mysql');

const bodyParser = require('body-parser');


const app = express();


// Create a connection to the database

const db = mysql.createConnection({

  host: 'your_host',

  user: 'your_username',

  password: 'your_password',

  database: 'your_database'

});


// Connect to the database

db.connect((err) => {

  if (err) {

    console.error('Error connecting to the database:', err);

    return;

  }

  console.log('Connected to the database');

});


// Parse JSON bodies

app.use(bodyParser.json());


// Define the API endpoint to list students with marks greater than 60

app.get('/api/students/high-achievers', (req, res) => {

  const query = 'SELECT * FROM student WHERE marks > 60';

  db.query(query, (err, results) => {

    if (err) {

      return res.status(500).json({ error: 'Error fetching students' });

    }


    res.json(results);

  });

});


// Start the server

const port = 3000;

app.listen(port, () => {

  console.log(Server started on port ${port});

});

Comments

Popular posts from this blog

Short