
Node.js and Express are essential tools for web development, especially for building server-side applications. Node.js is a runtime environment that allows JavaScript to run on the server, while Express is a web application framework that simplifies the process of setting up a server and handling requests. In this blog, we will explore how to get started with Node.js and Express, covering installation, basic setup, and creating a simple web server.
What is Node.js?
Node.js is an open-source, cross-platform runtime environment that allows developers to execute JavaScript code on the server-side. Unlike traditional server-side languages like PHP, Python, or Ruby, Node.js uses JavaScript, making it easier for web developers to use a single language for both client-side and server-side code.
Node.js is built on Google's V8 JavaScript engine and is designed for applications that require high performance and scalability, such as:
- Real-time data-intensive web applications
- Single-page applications (SPAs)
- APIs and microservices
- Chat and messaging applications
What is Express.js?
Express.js is a minimal and flexible Node.js web application framework that provides a robust set of features for web applications. It is designed to make web development faster, easier, and more robust. Express.js simplifies the process of routing, middleware use, and template rendering.
Installation
Before we dive into coding, let's set up Node.js and Express.js on your machine.
Installing Node.js
-
Download Node.js:
- Visit the official Node.js website and download the LTS (Long Term Support) version.
-
Install Node.js:
- Run the installer and follow the instructions.
-
Verify Installation:
- Open your terminal (or command prompt) and run the following command to check the Node.js version:
node -v
- You should see the version of Node.js that you just installed.
- Open your terminal (or command prompt) and run the following command to check the Node.js version:
Installing Express.js
Express.js is installed via npm (Node Package Manager), which comes with Node.js.
-
Create a Project Folder:
- Create a new folder for your project and navigate into it:
mkdir my-express-app cd my-express-app
- Create a new folder for your project and navigate into it:
-
Initialize a New Node.js Project:
- Run the following command to create a
package.json
file, which keeps track of your project's dependencies:npm init -y
- Run the following command to create a
-
Install Express.js:
- Run the following command to install Express.js:
npm install express
- Run the following command to install Express.js:
Setting Up Your First Express Application
Now that we have Node.js and Express.js installed, let's create a simple "Hello, World!" application.
-
Create an Application File:
- Create a new file named
app.js
in your project folder:touch app.js
- Create a new file named
-
Write Basic Express Code:
- Open
app.js
in your favorite code editor and add the following code:// Import the express library const express = require('express'); // Create an instance of express const app = express(); // Define a route for the home page app.get('/', (req, res) => { res.send('Hello, World!'); }); // Start the server const PORT = 3000; app.listen(PORT, () => { console.log(`Server is running on http://localhost:${PORT}`); });
- Open
-
Run Your Application:
- In your terminal, run the following command to start the server:
node app.js
- Open your web browser and go to
http://localhost:3000
. You should see "Hello, World!" displayed on the page.
- In your terminal, run the following command to start the server:
Understanding the Code
Let's break down the code we wrote in app.js
to understand what each part does.
Importing Express
const express = require('express');
This line imports the Express library and assigns it to the variable express
. The require
function is used to include external modules in Node.js.
Creating an Express Application
const app = express();
Here, we create an instance of an Express application. This instance will be used to define routes and middleware.
Defining Routes
app.get('/', (req, res) => {
res.send('Hello, World!');
});
This line defines a route for the root URL (/
). When a GET request is made to the root URL, the callback function is executed, and "Hello, World!" is sent as the response.
Starting the Server
const PORT = 3000;
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});
This code starts the server on port 3000. When the server is running, it logs a message to the console indicating where the server can be accessed.
Basic Concepts in Express.js
Before we proceed with more advanced topics, let's cover some of the basic concepts in Express.js.
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. Middleware can:
- Execute any code.
- Make changes to the request and the response objects.
- End the request-response cycle.
- Call the next middleware function in the stack.
Here's an example of a middleware function:
app.use((req, res, next) => {
console.log('Middleware function executed');
next();
});
Routing
Routing refers to determining how an application responds to a client request to a specific endpoint, which is a URI (or path) and an HTTP request method (GET, POST, etc.). Here’s an example of defining a simple route for a /about
page:
app.get('/about', (req, res) => {
res.send('About Page');
});
Serving Static Files
Express provides a middleware function express.static
to serve static files such as images, CSS files, and JavaScript files. To serve static files from the public
directory, use the following code:
app.use(express.static('public'));
Building a More Complex Application
Let's expand our application by adding more routes and serving static files.
Adding Routes
Create a new file named routes.js
and add the following code to define additional routes:
const express = require('express');
const router = express.Router();
router.get('/', (req, res) => {
res.send('Welcome to the Home Page');
});
router.get('/about', (req, res) => {
res.send('This is the About Page');
});
router.get('/contact', (req, res) => {
res.send('Contact us at contact@example.com');
});
module.exports = router;
app.js
Using the Router in Modify your app.js
file to use the routes defined in routes.js
:
const express = require('express');
const app = express();
const PORT = 3000;
// Import routes
const routes = require('./routes');
// Use the router
app.use('/', routes);
// Start the server
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});
Serving Static Files
Create a public
folder in your project directory and add a simple HTML file named index.html
:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>My Express App</title>
</head>
<body>
<h1>Welcome to My Express App</h1>
<p>This is a static HTML file.</p>
</body>
</html>
Modify app.js
to serve static files from the public
folder:
const express = require('express');
const app = express();
const PORT = 3000;
// Middleware to serve static files
app.use(express.static('public'));
// Import routes
const routes = require('./routes');
// Use the router
app.use('/', routes);
// Start the server
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});
Introduction to Templates
While serving static HTML files is fine for simple applications, most web applications require dynamic content. Express.js supports various template engines such as Pug, Handlebars, and EJS. In this tutorial, we'll use EJS.
Installing EJS
First, install EJS using npm:
npm install ejs
Setting Up EJS
Modify app.js
to use EJS as the template engine:
const express = require('express');
const app = express();
const PORT = 3000;
// Set EJS as the templating engine
app.set('view engine', 'ejs');
// Middleware to serve static files
app.use(express.static('public'));
// Import routes
const routes = require('./routes');
// Use the router
app.use('/', routes);
// Start the server
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});
Creating an EJS Template
Create a views
folder in your project directory and add a file named index.ejs
:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title><%= title %></title>
</head>
<body>
<h1>Welcome to <%= message %></h1>
</body>
</html>
Modify the home route in routes.js
to render the index.ejs
template:
const express = require('express');
const router = express.Router();
router.get('/', (req, res) => {
res.render('index', { title: 'My Express App', message: 'Welcome to the Home Page' });
});
router.get('/about', (req, res) => {
res.send('This is the About Page');
});
router.get('/contact', (req, res) => {
res.send('Contact us at contact@example.com');
});
module.exports = router;
Restart your server and navigate to http://localhost:3000
. You should see the rendered EJS template with dynamic content.
Middlewares in Express
Middleware functions are an essential part of Express.js applications. Here are some common types of middleware:
Application-Level Middleware
These middleware functions are bound to the application object using app.use()
or app.METHOD()
where METHOD is the HTTP method of the request.
// Log every request to the console
app.use((req, res, next) => {
console.log(`${req.method} request for '${req.url}'`);
next(); // Move to the next middleware or route handler
});
Router-Level Middleware
These middleware functions are bound to an instance of express.Router()
.
const router = express.Router();
// Send a middleware function to the router
router.use((req, res, next) => {
console.log('Time:', Date.now());
next();
});
router.get('/', (req, res) => {
res.send('Hello, World!');
});
module.exports = router;
Handling POST Requests
In addition to handling GET requests, you can also handle POST requests and other HTTP methods using Express.js.
Create a new form in your public
folder named contact.html
:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Contact Us</title>
</head>
<body>
<h1>Contact Us</h1>
<form action="/submit-contact" method="POST">
<label for="name">Name:</label>
<input type="text" id="name" name="name" required>
<br>
<label for="email">Email:</label>
<input type="email" id="email" name="email" required>
<br>
<button type="submit">Submit</button>
</form>
</body>
</html>
Modify routes.js
to handle POST requests:
const express = require('express');
const router = express.Router();
const bodyParser = require('body-parser');
// Middleware to parse request bodies
router.use(bodyParser.urlencoded({ extended: true }));
router.get('/', (req, res) => {
res.render('index', { title: 'My Express App', message: 'Welcome to the Home Page' });
});
router.get('/about', (req, res) => {
res.send('This is the About Page');
});
router.get('/contact', (req, res) => {
res.sendFile(__dirname + '/public/contact.html');
});
router.post('/submit-contact', (req, res) => {
const { name, email } = req.body;
res.send(`Thank you ${name} for contacting us. We have received your email at ${email}.`);
});
module.exports = router;
Restart your server and navigate to http://localhost:3000/contact
to see the contact form. Submitting the form will trigger the POST request and send a response back to the user.
Conclusion
In this blog, we covered the basics of setting up a Node.js and Express.js application, creating routes, serving static files, using templates, and handling middleware and POST requests. Express.js provides a powerful and flexible framework that makes it easy to build robust web applications. As you continue to learn more about Express, you can explore more advanced topics such as authentication, database integration, and RESTful APIs.
Feel free to experiment with the application and build upon what we've covered. Happy coding!