Node.js is a JavaScript runtime built on Chrome's V8 JavaScript engine that allows developers to run JavaScript code on the server side. It is event-driven, non-blocking, and designed to build scalable network applications. Node.js allows the development of fast, lightweight, and highly scalable server-side applications, making it an ideal choice for real-time applications such as chat apps, streaming services, and APIs.
Express.js is a minimal and flexible Node.js web application framework that simplifies the development of web servers and APIs. It provides a robust set of features, including routing, middleware support, and templates, which make handling HTTP requests and responses more efficient. Express allows developers to focus on writing application logic without worrying about low-level server details. It is widely used for building RESTful APIs, single-page applications, and server-side rendered applications.
Learning outcomes:
Backend Server Setup: Node.js is used to set up the backend server, while Express.js handles the routing and middleware logic to process HTTP requests, making it easy to handle endpoints like GET and POST requests for various functionalities like login, registration, and data retrieval.
Serving Static Assets: The Express framework's express.static middleware is employed to serve static files such as HTML, CSS, and JavaScript, allowing the smooth presentation of frontend assets like styling and interactive components.
Request Body Parsing: The body-parser middleware is integrated to parse incoming request bodies, simplifying the handling of form data. This ensures that user inputs, such as login credentials or form submissions, can be easily accessed via req.body.
User Authentication and Security: The implementation of user authentication allows users to sign up and log in securely. Passwords are hashed using libraries like bcryptjs, ensuring the protection of user data and preventing the storage of plain-text passwords.
Dynamic Data Rendering: Routes like /students or /courses generate dynamic content by fetching data from the database. This data is then displayed based on the user's role (e.g., student or instructor), creating a personalized experience.
Error Management and Validation: Error handling techniques are applied to manage common issues like invalid credentials or database query failures. This ensures users are informed of problems in a clear and helpful manner, maintaining a smooth user experience.
DATABASE.
const mysql = require('mysql');
const con = mysql.createConnection({
host: "localhost",
user: "root",
password: ""
});
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
con.query("CREATE DATABASE IF NOT EXISTS course", function(err, result) {
if (err) throw err;
console.log("Database 'course' created or already exists.");
con.query("USE course", function(err, result) {
if (err) throw err;
console.log("Using the 'course' database.");
const coursesTable = `
CREATE TABLE IF NOT EXISTS courses (
course_id INT PRIMARY KEY,
course_name VARCHAR(255),
instructor_id INT ,
duration VARCHAR(255) ,
prize int
)`;
con.query(coursesTable, function(err, result) {
if (err) throw err;
console.log("Table 'courses' created or already exists.");
});
const instr_table = `
CREATE TABLE IF NOT EXISTS instructors (
instructors_id INT PRIMARY KEY,
instructor_name VARCHAR(255)
)`;
con.query(instr_table, function(err, result) {
if (err) throw err;
console.log("Table 'instructors' created or already exists.");
});
});
});
});
INSERT.js:
const mysql = require('mysql');
const con = mysql.createConnection({
host: "localhost",
user: "root",
password: "",
database: "course"
});
con.connect(function(err) {
if (err) throw err;
console.log("Connected to MySQL!");
const insertcourses = `
INSERT INTO courses (course_id, course_name, instructor_id , duration , prize )
VALUES
(1, 'a',1,'2h',200),
(2, 'b',2,'2h',300),
(3, 'c',3,'2h',400),
(4, 'd',1,'2h',500),
(5, 'e',2,'2h',600)
`;
con.query(insertcourses, function(err, result) {
if (err) throw err;
console.log("Inserted courses into the 'courses' table.");
const insertinstructors = `
INSERT INTO instructors (instructors_id,instructor_name)
VALUES
(1,'koushik'),
(2,'kumar'),
(3,'reddy')
`;
con.query(insertinstructors, function(err, result) {
if (err) throw err;
console.log("Inserted instructors into the 'instructors' table."); });
});
});
SERVER.js :
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var mysql = require('mysql');
app.use(bodyParser.urlencoded({ extended: true }));
var db = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '',
database: 'course'
});
db.connect(function(err) {
if (err) {
console.error('Database connection failed:', err.stack);
return;
}
console.log('Connected to database');
});
app.get('/', function(req, res) {
res.send("hello welcome");
});
app.get('/courses', function(req, res) {
const sql = \`
SELECT c.course_id, c.course_name, i.instructor_name
FROM courses c
JOIN instructors i ON i.instructors_id = c.instructor_id;
\`;
db.query(sql, function(err, results) {
if (err) {
console.error(err);
}
res.json(results);
});
});
app.get('/update-course', function (req, res) {
var formHtml = "";
formHtml += "";
formHtml += "
";
formHtml += "course ID:
";
formHtml += "";
formHtml += "
";
formHtml += "";
formHtml += "";
res.send(formHtml);
});
app.post('/update-course', function (req, res) {
var course_id = req.body.course_id;
const sql = `update courses set prize = 700 WHERE course_id = ?`;
db.query(sql, [course_id], function (err, result) {
if (err) {
console.error(err)
}
res.send("updated")
});
});
app.get('/delete-course', function (req, res) {
var formHtml = "";
formHtml += "";
formHtml += "
";
formHtml += "course ID:
";
formHtml += "";
formHtml += "
";
formHtml += "";
formHtml += "";
res.send(formHtml);
});
app.post('/delete-course', function (req, res) {
var course_id = req.body.course_id;
const sql = `delete from courses WHERE course_id = ?`;
db.query(sql, [course_id], function (err, result) {
if (err) {
console.error(err)
}
res.send("deleted")
});
});
app.get('/add-course', function (req, res) {
var formHtml = "";
formHtml += "";
formHtml += "
";
formHtml += "course ID:
";
formHtml += "course Name:
";
formHtml += "instructor ID:
";
formHtml += "duration:
";
formHtml += "Prize:
";
formHtml += "";
formHtml += "
";
formHtml += "";
formHtml += "";
res.send(formHtml);
});
app.post('/add-course', function (req, res) {
var course_id = req.body.course_id;
var name = req.body.name;
var instructor_id = req.body.instructor_id;
var duration = req.body.duration;
var prize = req.body.prize;
const sql = `
INSERT INTO courses (course_id, course_name, instructor_id , duration , prize )
VALUES (?, ?, ?, ?,?);
`;
db.query(sql, [course_id,name,instructor_id,duration,prize], function (err, result) {
if (err) {
console.error(err);
} else {
res.send("added");
}
});
});
app.listen(3000, function() {
console.log('Server is running on http://localhost:3000');
});