Introduction to Node.js and Express
Why Learn Node.js and Express?
- ★ So far, we have used HTML/CSS/JavaScript for the front end, PHP for the back end, and MySQL for the database.
- ★ Node.js + Express is a modern way to build the server side of web applications.
- ★ It allows developers to use JavaScript on both the front end and the back end.
- ★ This makes it easier to build applications where React talks to an API and the API talks to MySQL.
What is Node.js?
- ★ Node.js is a JavaScript runtime environment.
- ★ It lets us run JavaScript outside the browser.
- ★ With Node.js, JavaScript can be used to create a web server, read files, connect to databases, and build APIs.
- ★ It is commonly used for modern full-stack development.
What is Express?
- ★ Express is a lightweight framework built on top of Node.js.
- ★ It makes it easier to create routes, handle requests, and send responses.
- ★ Express helps us build a backend API quickly.
PHP vs Node.js/Express
| PHP Approach |
Node.js / Express Approach |
| Runs with Apache/XAMPP |
Runs with Node.js |
| Backend language is PHP |
Backend language is JavaScript |
| Often mixes PHP with HTML |
Often sends JSON data to the frontend |
| Frontend can submit forms directly to PHP pages |
Frontend can call API routes such as /students |
| HTML → PHP → MySQL |
React → Express → MySQL |
Step 1: Create a Node Project
- ★ First, create a new folder for your project.
- ★ Then initialize the project using npm init -y.
- ★ Install Express with npm install express.
Commands:
mkdir nodeapp
cd nodeapp
npm init -y
npm install express
Step 2: Create Your First Express Server
- ★ Create a file named index.js.
- ★ Add the following code:
index.js:
const express = require('express');
// Import the Express library
const app = express();
// Create an Express application (this is our server)
app.get('/', (req, res) => {
// Define a route for the homepage "/"
// req = request from the browser
// res = response sent back to the browser
res.send('Hello from Express!');
// Send a response (text or HTML) to the browser
});
app.listen(3000, () => {
// Start the server on port 3000
console.log('Server running at http://localhost:3000');
// Print a message in the terminal
});
How to Run the Server
node index.js
- ★ Open your browser and go to http://localhost:3000.
- ★ You should see: Hello from Express!
Important: Restart the Server
- ★ When you change your code, Node.js does NOT automatically reload.
- ★ You must stop and restart the server to see changes.
Steps:
Ctrl + C (stop server)
node index.js (restart server)
What is a Route?
- ★ A route is a URL path handled by the server.
- ★ For example, /, /students, and /course are routes.
- ★ Express uses methods like app.get() to define routes.
Example:
app.get('/students', (req, res) => {
res.json([
{ id: 1, name: 'Alice' },
{ id: 2, name: 'Bob' }
]);
});
app.get('/course', (req, res) => {
res.send('<h1>Course Page</h1>');
});
Then visit:
- /students -> JSON (shows data, not a webpage)
- /course -> HTML page
What is JSON?
- ★ JSON stands for JavaScript Object Notation.
- ★ It is a common data format used for communication between frontend and backend.
- ★ React often receives data from the server in JSON format.
Connecting Express to MySQL
- ★ We can connect Express to the same MySQL database we already used with PHP.
- ★ Install the MySQL package for Node.js:
npm install mysql2
Example:
const express = require('express');
const mysql = require('mysql2');
const app = express();
const db = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '',
database: 'school'
});
app.get('/students', (req, res) => {
db.query('SELECT * FROM students', (err, results) => {
if (err) {
res.status(500).send(err.message);
return;
}
res.json(results);
});
});
app.listen(3000, () => {
console.log('Server running at http://localhost:3000');
});
How the Modern Stack Works
- ★ React is the frontend.
- ★ Express is the backend server.
- ★ MySQL stores the data.
| Layer |
Technology |
Job |
| Frontend |
React |
Displays pages and user interface |
| Backend |
Node.js + Express |
Handles requests and sends data |
| Database |
MySQL |
Stores application data |
Frontend Calling Express (Using HTML)
- ★ We can use a simple HTML file to request data from Express.
- ★ We will use fetch() in a browser to call our backend.
Step 1: Create a public Folder
- ★ Inside your Node project, create a folder named public.
- ★ This folder will store frontend files like HTML.
Step 2: Create test.html
- ★ Inside the public folder, create a file named test.html.
<!DOCTYPE html>
<html>
<head>
<title>Students</title>
</head>
<body>
<h1>Students</h1>
<ul id="studentsList"></ul>
<script>
fetch('http://localhost:3000/students')
.then(response => response.json())
.then(data => {
const list = document.getElementById('studentsList');
data.forEach(student => {
const li = document.createElement('li');
li.textContent = student.name;
list.appendChild(li);
});
})
.catch(error => console.error(error));
</script>
</body>
</html>
Step 3: Update index.js
- ★ Tell Express to serve files from the public folder.
app.use(express.static('public')); //Make the public folder available to the browser as static files
Step 4: Run and Test
node index.js
- ★ Open your browser and go to:
- ★ http://localhost:3000/test.html
- ★ You should see student names displayed on the page.
Important Idea: API-Based Development
- ★ In older projects, the server often returned full HTML pages.
- ★ In modern applications, the backend often returns JSON data instead.
- ★ The frontend uses that data to build the page dynamically.
Summary
- ★ Node.js lets us run JavaScript on the server.
- ★ Express helps us build a web server and handle routes.
- ★ We can connect Express to a MySQL database to retrieve and manage data.
- ★ Express can return either JSON data or HTML content.
- ★ Using res.json() sends data, while res.send() can display a webpage.
- ★ We can also use a simple HTML file with fetch() to request data from Express.
- ★ This approach demonstrates how the frontend (HTML) communicates with the backend (Express).