Certainly! Let's start from the basics and build up to creating a simple Express application using Node.js.
1. What is Node.js?
Node.js is a runtime environment that allows you to run JavaScript on the server side. Unlike traditional JavaScript, which runs in a browser, Node.js lets you execute JavaScript code on a server. It's built on Chrome's V8 JavaScript engine and provides a variety of modules to handle file systems, networks, and more.
2. Installing Node.js
Before you can use Node.js or Express, you need to install Node.js. Here’s how:
Download the LTS (Long Term Support) version, which is recommended for most users.
Install Node.js:
Run the installer and follow the prompts.
Verify the installation by opening your terminal (Command Prompt, PowerShell, or a Unix-based terminal) and running:
sh
node -v
This should return the installed Node.js version, e.g., v16.13.0.
Verify npm installation:
Npm (node package manager) is installed alongside node.js. Verify the installation by running:
sh
npm -v
This should return the installed npm version, e.g. 8.1.0
3. Creating a Node.js Project
Let's create a simple Node.js project.
Create a Project Directory:
sh
mkdir my-node-app
cd my-node-app
Initialize a Node.js Project:
sh
npm init -y
This command creates a package.json file with default values, which is used to manage project dependencies and scripts.
Create an entry point file:
sh
touch index.js
This will be the main file where we will write our node.js code.
Write Your First Node.js Script:
Open index.js in your favourite text editor and add the following code:
js
console.log('Hello, Node.js!');
Run Your Node.js Script:
sh
node index.js
You should see Hello, Node.js! printed in your terminal.
4. Introduction to Express
Express is a minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications. It simplifies the process of building web servers and APIs.
5. Installing Express
To use Express in your project, you need to install it via npm.
Install Express:
sh
npm install express
This command adds Express to your node_modules directory and lists it as a dependency in your package.json.
6. Creating an Express Application
Now, let's create a simple Express application.
Modify index.js:
Replace the contents of index.js with the following code:
js
const express = require('express');
const app = express();
const port = 3000;
// Define a route for the root URL
app.get('/', (req, res) => {
res.send('Hello, Express!');
});
// Start the server
app.listen(port, () => {
console.log(`Server is running at http://localhost:${port}`);
});
Understand the Code:
require('express'): Imports the Express module.
express(): Creates an Express application instance.
app.get('/'): Defines a route handler for GET requests to the root URL (/). When this route is accessed, it sends the response Hello, Express!.
app.listen(port): Starts the server and listens on the specified port (3000). When the server starts, it logs a message to the console.
Run Your Express Application:
sh
node index.js
You should see Server is running at http://localhost:3000 in your terminal.
Test Your Application:
Open your web browser.
Navigate to http://localhost:3000.
You should see Hello, Express! displayed on the page.
7. Adding More Routes
Let's add a few more routes to our Express application.
Modify index.js:
Add the following routes to index.js:
js
// Route for /about
app.get('/about', (req, res) => {
res.send('This is the about page.');
});
// Route for /contact
app.get('/contact', (req, res) => {
res.send('This is the contact page.');
});
Test the New Routes:
Navigate to http://localhost:3000/about to see the about page.
Navigate to http://localhost:3000/contact to see the contact page
8. Using Middleware
Middleware functions are functions that have access to the request object (req), the response object (res), and the next middleware function in the application’s request-response cycle.
Let's add a simple logger middleware to log each request.
Modify index.js:
Add the following middleware before defining your routes:
js
// Logger middleware
app.use((req, res, next) => {
console.log(`${req.method} ${req.url}`);
next(); // Pass control to the next middleware function
});
Test the Middleware:
Refresh the pages or navigate to different routes.
You should see logs in your terminal for each request, e.g., GET /, GET /about, GET /contact.
9. Serving Static Files
Express can also serve static files such as HTML, CSS, and JavaScript. Let's serve some static files.
Create a public Directory:
sh
mkdir public
Add Static Files:
Create an index.html file in the public directory:
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Express App</title>
</head>
<body>
<h1>Welcome to Express App</h1>
<p>This is a static HTML file served by Express.</p>
</body>
</html>
Modify index.js:
Use the express.static middleware to serve files from the public directory.
js
// Serve static files from the 'public' directory
app.use(express.static('public'));
// Define a route for the root URL
app.get('/', (req, res) => {
res.sendFile(__dirname + '/public/index.html');
});
Test Serving Static Files:
Navigate to http://localhost:3000.
You should see the content of index.html displayed in your browser.
10. Handling POST Requests
Express can also handle POST requests, which are commonly used for forms and API endpoints.
Install Body-Parser:
Body-parser is a middleware that parses the body of an incoming request. As of Express 4.16.0, body-parser is included with Express, so you can use it directly.
sh
npm install body-parser
Modify index.js:
Add the following code to handle a POST request:
js
const bodyParser = require('body-parser');
// Use body-parser middleware to parse JSON bodies
app.use(bodyParser.json());
// Define a POST route
app.post('/submit', (req, res) => {
console.log(req.body); // Log the request body
res.send('POST request received!');
});
Test the POST Request:
You can use a tool like Postman to send a POST request to http://localhost:3000/submit with a JSON body.
Alternatively, you can create a simple HTML form to test the POST request.