Corporate Training
Request Demo
Click me
Menu
Let's Talk
Request Demo

Tutorials

Express.js for Building Web Applications

Express.js for Building Web Applications

Express.js is a popular web application framework for Node.js that simplifies the process of building web applications and APIs. It provides a set of powerful features and middleware for routing, handling requests and responses, and much more. Here's an overview of Express.js and how to use it to build web applications:

1. Installing Express.js:

Before using Express.js, you need to install it. In your project directory, run the following command using npm:

npm install express
 

2. Creating an Express Application:

To create an Express application, require the Express module and create an instance of the application.

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

3. Defining Routes:

Express allows you to define routes for handling HTTP requests. You can specify the HTTP method (GET, POST, PUT, DELETE, etc.) and the URL path that each route should match.

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

app.get('/about', (req, res) => {
  res.send('About Us');
});
 

4. Middleware:

Middleware functions are essential in Express.js. They can be used to perform tasks such as logging, authentication, and data parsing. Middleware functions are executed in the order they are added to the application.

// Example middleware function
app.use((req, res, next) => {
  console.log('Request received at:', new Date());
  next(); // Call the next middleware or route handler
});
 

5. Request and Response Objects:

Express provides request (req) and response (res) objects that carry information about the HTTP request and allow you to send a response back to the client.

app.get('/user/:id', (req, res) => {
  const userId = req.params.id;
  res.send(`User ID: ${userId}`);
});
 

6. Template Engines:

Express can work with template engines like EJS, Handlebars, or Pug to dynamically render HTML templates and serve dynamic content.

app.set('view engine', 'ejs'); // Example with EJS

app.get('/profile', (req, res) => {
  res.render('profile', { username: 'john_doe' });
});
 

7. Static Files:

You can serve static files (e.g., CSS, JavaScript, images) using the built-in express.static middleware.

app.use(express.static('public'));
 

8. Error Handling:

Express provides mechanisms for error handling, including custom error handlers and error middleware.

app.use((err, req, res, next) => {
  console.error(err.stack);
  res.status(500).send('Something broke!');
});
 

9. Starting the Server:

Finally, start the Express application by listening on a specific port.

const port = process.env.PORT || 3000;

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