Working with Express.js

Introduction

Express.js is a popular web application framework for Node.js that simplifies the development of web applications. In this article, we'll explore the basics of Express.js, explain how to set up a new Express application, and cover essential features like routing, middleware, and templating.

What is Express.js?

Express.js is a minimal, unopinionated web application framework for Node.js that provides essential features for building web applications, APIs, and microservices. Express.js simplifies the development process by handling common tasks like routing, request processing, and response generation.

Setting Up an Express.js Application

1. Install Express.js

First, you need to install Express.js as a dependency in your Node.js project. Open your terminal, navigate to your project folder, and run the following command:

npm install express

2. Create an Express.js Application

Create a new file called app.js and add the following code to set up a basic Express.js application:

const express = require('express');
const app = express();
const PORT = 3000;

app.get('/', (req, res) => {
    res.send('Hello, World!');
});

app.listen(PORT, () => {
    console.log(Server is running on port ${PORT});
});

Routing in Express.js

Routing is the process of defining how an application responds to specific client requests. Express.js provides a simple way to define routes using HTTP methods (like GET, POST, PUT, and DELETE) and URL patterns. Here's an example of defining a few basic routes:

app.get('/users', (req, res) => {
    // Retrieve and send the list of users
});

app.post('/users', (req, res) => {
    // Create a new user
});

app.put('/users/:id', (req, res) => {
    // Update the user with the specified ID
});

app.delete('/users/:id', (req, res) => {
    // Delete the user with the specified ID
});

Middleware in Express.js

Middleware functions are functions that have access to the request object (req), the response object (res), and the next function in the application's request-response cycle. Middleware can perform tasks like modifying the request or response, logging, authentication, and more. Here's an example of a simple logging middleware:

function logger(req, res, next) {
    console.log(${req.method} ${req.originalUrl});
    next();
}

app.use(logger);

Templating in Express.js

Express.js supports various templating engines, such as EJS, Pug, and Handlebars, which allow you to generate HTML dynamically based on data. Let's see how to set up EJS as the templating engine in your Express.js application.

1. Install EJS

First, install EJS as a dependency in your project by running the following command:

npm install ejs

2. Set Up EJS in Express.js

In your app.js file, add the following lines to set up EJS as the templating engine:

app.set('view engine', 'ejs');
app.set('views', 'views');

3. Create an EJS Template

Create a new folder named views and a new file called index.ejs inside it. Add the following code to create a simple EJS template:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Express.js with EJS</title>
</head>
<body>
<h1>Welcome, <%= name %>!</h1>
</body>
</html>

4. Render the EJS Template

In your app.js file, modify the route handler for the root path ('/') to render the EJS template:

app.get('/', (req, res) => {
    res.render('index', { name: 'John Doe' });
});

Conclusion

In this article, we've explored the basics of Express.js, learned how to set up a new Express application, and covered essential features like routing, middleware, and templating. By leveraging Express.js, you can build web applications in Node.js quickly and efficiently.

Table of Contents: Node.js for Beginners

  1. Getting Started with Node.js - A Comprehensive Guide
  2. Understanding Node.js Modules
  3. Working with Express.js
  4. Node.js: Event-Driven Architecture
  5. Handling File System in Node.js
  6. Node.js and Databases
  7. Node.js Authentication and Security
  8. Deploying Node.js Applications
  9. Testing and Debugging Node.js
  10. Best Practices for Node.js Development