Express.js:-
-Express.js was originally created by TJ Holowaychuk in 2010.
-Express.js is a web framework for Node.js.
-It is an open-source
-Express.js is a fast, lightweight, and flexible web application framework for Node.js.
-It is mainly used to create web servers, REST APIs, and backend applications using JavaScript.
-Features: Routing, middleware, REST API support, request/response handling, template engines, database integration, and flexibility.
-Applications: Web applications, REST APIs, e-commerce systems, authentication systems, real-time applications, and microservices.
Works:-
-----
Your Application
↓
Express.js
↓
Node.js
↓
Operating System
Version Year Features
--------- ----- -------------
Express 1.x 2010 Early versions of Express
Express 2.x 2011 Improved routing and middleware
Express 3.x 2012 Added several web-development features
Express 4.x 2014 Major redesign; middleware became more modular
Express 5.x 2024 Modern release with improved Promise/async handling
Difference Between Node.js and Express.js
Node.js Express.js
--------- ------------
-Developed initially by Ryan Dahl. - Originally created by TJ Holowaychuk.
-Node.js is a JavaScript runtime environment. - Express.js is a web framework.
-It allows JavaScript to run outside the browser.- It runs on top of Node.js.
-Provides low-level APIs for HTTP, files, networking- Provides easier tools for routing, middleware,
and HTTP handling.
-Can create servers without Express.js. -Requires Node.js to run.
-More code may be required for web-server development-Simplifies web-server and API development.
-Example: http.createServer() Example: app.get()
Ex: Ex:
const http = require("http"); - const express = require("express");
const server = http.createServer((req, res) => { const app = express();
res.end("Hello World"); app.get("/", (req, res) => {
}); res.send("Hello World");
server.listen(3000); });
app.listen(3000);
------------------------------------------------------------------------------
install and use:-
step1: first install Node.js.
(https://nodejs.org/en/download)
step2: (After installing, open Terminal / Command Prompt and check:)
node -v
npm -v
step3: (Create a project folder
Open your terminal and run:)
1. mkdir my-express-app
2. cd my-express-app
step4: (Initialize a Node.js project)
npm init -y
This creates a package.json file.
Your project now looks like:
my-express-app/
└── package.json
step5: (Install Express.js)
npm install express
This installs Express locally in your project.
You'll now have something like:
my-express-app/
├── node_modules/
├── package-lock.json
└── package.json
step6: (Create your Express server)
-copy con app.js
const express = require("express");
const app = express();
const PORT = 3000;
app.get("/", (req, res) => {
res.send("Hello World!");
});
app.listen(PORT, () => {
console.log(`Server running at http://localhost:3000`);
});
----------(ctlr+z==save)-----------
working:
--------
Line 1: imports Express
Line 2: This creates your Express application
Line 3: This creates a route
Here:
-app.get() → handles an HTTP GET request
-"/" → the URL path
-req → request from the client
-res → response sent back to the client
-res.send() → sends data back to the browser
-And this starts your server:
app.listen(3000, () => {
console.log("Server started");
});
step7: Start the server
node app.js
You should see:
Server running at http://localhost:3000
step8: (Open your browser and go to:)
http://localhost:3000
step9 : (stop server : ctrl+c)
=============================
Ex1:(copy con app.js)
const express = require("express");
const app = express();
const PORT = 3000;
// Middleware
app.use(express.json());
// Home route
app.get("/", (req, res) => {
res.send("Welcome to my Express API!");
});
// About route
app.get("/about", (req, res) => {
res.send("About page");
});
// GET API
app.get("/api/users", (req, res) => {
res.json([
{ id: 1, name: "John" },
{ id: 2, name: "Jane" }
]);
});
// POST API
app.post("/api/users", (req, res) => {
const user = req.body;
res.json({
message: "User created successfully",
user: user
});
});
// Start server
app.listen(PORT, () => {
console.log(`Server running at http://localhost:${PORT}`);
});
--------save : (press ctrl+z)-------------
-------run server : node app.js-----------
---------browse URL : http://localhost:3000---------
http://localhost:3000/about
http://localhost:3000/api/users
*********************************************************************
Database connectivity
---------------------
-connect mysql+express.js
The HTML does not connect directly to MySQL.
HTTP Request
HTML ──────────────────────────> Express.js
│
│ SQL Query
↓
MySQL
│
│ Result
↓
HTML <──────────────────────── Express.js
1. Project structure
my-project/
│
├── server.js
├── db.js
├── .env
├── package.json
│
└── public/
└── index.html
---------------------------
step1: open command prompt
cd my-express-app
step2: npm init -y
npm install express mysql2 dotenv
step3: create a .env file
DB_HOST=localhost
DB_USER=root
DB_PASSWORD=""
DB_NAME=test
DB_PORT=3306
step4: create db.js
const mysql = require("mysql2/promise");
require("dotenv").config();
const pool = mysql.createPool({
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME,
port: process.env.DB_PORT
});
module.exports = pool;
step5:create server.js
const express = require("express");
const path = require("path");
const pool = require("./db");
const app = express();
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
app.use(express.static(path.join(__dirname, "public")));
// Insert user into MySQL
app.post("/add-user", async (req, res) => {
try {
const { roll, name, city } = req.body;
const sql = `
INSERT INTO register1 (roll, name, city)
VALUES (?, ?, ?)
`;
await pool.execute(sql, [roll, name, city]);
res.send("User added successfully!");
} catch (error) {
console.error(error);
res.status(500).send("Database error");
}
});
// Get users
app.get("/users", async (req, res) => {
try {
const [rows] = await pool.query("SELECT * FROM register1");
res.json(rows);
} catch (error) {
console.error(error);
res.status(500).send("Database error");
}
});
app.listen(3000, () => {
console.log("Server running at http://localhost:3000");
});
step6: create a html (client)
<!DOCTYPE html>
<html>
<head>
<title>MySQL + Express</title>
</head>
<body>
<h1>User Registration</h1>
<form action="/add-user" method="POST">
<label>Roll:</label>
<input type="text" name="roll" required>
<br>
<label>Name:</label>
<input type="text" name="name" required>
<br>
<label>City:</label>
<input type="text" name="city" required>
<br>
<button type="submit">Save User</button>
</form>
<br>
</body>
</html>
step7: start the server
node server.js
==========================================
View Records
------------
step1 : create app.js
const express = require("express");
const mysql = require("mysql2");
const app = express();
const db = mysql.createConnection({
host: "localhost",
user: "root",
password: "",
database: "test"
});
db.connect((err) => {
if (err) {
console.error("MySQL connection failed:", err.message);
return;
}
console.log("Connected to MySQL");
});
// View all records
app.get("/view", (req, res) => {
const sql = "SELECT * From register1";
db.query(sql, (err, results) => {
if (err) {
return res.status(500).json({
error: err.message
});
}
res.json(results);
});
});
app.listen(3000, () => {
console.log("Server running at http://localhost:3000");
});
step2: node app.js
step3: http://localhost:3000/view
=====================================
View Specific Record
--------------------
step1 : create app.js
const express = require("express");
const mysql = require("mysql2");
const path = require("path");
const app = express();
const db = mysql.createConnection({
host: "localhost",
user: "root",
password: "",
database: "test"
});
app.use(express.static(path.join(__dirname, "public")));
// View a particular Record
app.get("/view", (req, res) => {
const id = req.query.roll;
const sql = "SELECT * FROM register1 WHERE roll = ?";
db.query(sql, [id], (err, results) => {
if (err) {
return res.status(500).send("Database error");
}
if (results.length === 0) {
return res.status(404).send(`
<h2>Record not found</h2>
<a href="/">Go Back</a>
`);
}
const emp = results[0];
res.send(`
<!DOCTYPE html>
<html>
<head>
<title>Details</title>
</head>
<body>
<h2>Details</h2>
<table border="1" cellpadding="10">
<tr>
<th>Roll</th>
<td>${emp.roll}</td>
</tr>
<tr>
<th>Name</th>
<td>${emp.name}</td>
</tr>
<tr>
<th>City</th>
<td>${emp.city}</td>
</tr>
</table>
<br>
<a href="/">Search Another Record</a>
</body>
</html>
`);
});
});
app.listen(3000, () => {
console.log("Server running at http://localhost:3000");
});
step2: create a index.html
<!DOCTYPE html>
<html>
<head>
<title>View Records</title>
</head>
<body>
<h2>Search Record by Roll</h2>
<form action="/view" method="GET">
<label>Enter Roll:</label>
<input type="number" name="roll" required>
<button type="submit">View Record</button>
</form>
</body>
</html>
step3: node app.js
step4: http://localhost:3000
======================================
Login Form
-----------
step1 : create a login.html
<!DOCTYPE html>
<html>
<head>
<title>Login Form</title>
<style>
body {
font-family: Arial, sans-serif;
background: #f2f4f8;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
}
.login-box {
background: white;
padding: 30px;
width: 300px;
border-radius: 10px;
box-shadow: 0 4px 15px #ccc;
}
h2 {
text-align: center;
}
input, button {
box-sizing: border-box;
width: 100%;
padding: 12px;
margin: 10px 0;
}
button {
background: #2563eb;
color: white;
border: none;
cursor: pointer;
}
button:hover {
background: #1d4ed8;
}
</style>
</head>
<body>
<div class="login-box">
<h2>Login</h2>
<form action="/login" method="POST">
<input type="text" name="username" placeholder="Username" required>
<input type="password" name="password" placeholder="Password" required>
<button type="submit">Login</button>
</form>
</div>
</body>
</html>
step2: create a app.js
const express = require("express");
const mysql = require("mysql2");
const path = require("path");
const app = express();
app.use(express.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname, "public")));
const db = mysql.createConnection({
host: "localhost",
user: "root",
password: "",
database: "test"
});
db.connect((err) => {
if (err) {
console.error("Database connection failed:", err.message);
return;
}
console.log("MySQL connected");
});
// Display login form
app.get("/", (req, res) => {
res.sendFile(path.join(__dirname, "public", "login.html"));
});
// Validate login
app.post("/login", (req, res) => {
const { username, password } = req.body;
const sql = `SELECT id, username FROM users WHERE username = ? AND password = ?`;
db.query(sql, [username, password], (err, results) => {
if (err) {
return res.status(500).send("Database error");
}
if (results.length > 0) {
return res.send(`
<h2>Login Successful!</h2>
<p>Welcome, ${username}</p>
`);
}
res.status(401).send(`
<h2>Invalid username or password</h2>
<a href="/">Try Again</a>
`);
});
});
app.listen(3000, () => {
console.log("Server running at http://localhost:3000");
});
step3: node app.js
step4: http://localhost:3000/login.html
===========================================
No comments:
Post a Comment