DEV Community

Cover image for Express.js Tutorial with Examples
kiraaziz
kiraaziz

Posted on

Express.js Tutorial with Examples

Welcome to the Express.js tutorial! Express.js is a popular web application framework for Node.js that simplifies the process of building robust and scalable web applications. In this tutorial, we will cover the basics of Express.js along with numerous examples to help you get started.

Table of Contents

  1. Installation
  2. Basic Setup
  3. Routing
  4. Middleware
  5. Static Files
  6. Template Engines
  7. Error Handling
  8. API Endpoints

Let's dive right in!

1. Installation

First, make sure you have Node.js and npm (Node Package Manager) installed. You can download them from the official Node.js website.

To create a new Express.js application, open your terminal and run the following command:

npm install express --save
Enter fullscreen mode Exit fullscreen mode

2. Basic Setup

Create a new file named app.js and add the following code:

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

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

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

Run the application using:

node app.js
Enter fullscreen mode Exit fullscreen mode

Visit http://localhost:3000 in your browser to see the "Hello, Express!" message.

3. Routing

Express allows you to define routes for different URLs. Add the following code to app.js:

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

app.get('/contact', (req, res) => {
  res.send('Contact Page');
});
Enter fullscreen mode Exit fullscreen mode

4. Middleware

Middleware functions are executed before the main request handler. They are used for tasks such as authentication, logging, etc. Create a simple middleware:

const logger = (req, res, next) => {
  console.log(`Visited: ${req.url}`);
  next();
};

app.use(logger);
Enter fullscreen mode Exit fullscreen mode

5. Static Files

Serve static files like CSS, images, and JavaScript using the express.static middleware. Create a public folder in your project directory and place your static files there.

app.use(express.static('public'));
Enter fullscreen mode Exit fullscreen mode

6. Template Engines

Express can render dynamic content using template engines like EJS or Pug. Install the EJS template engine:

npm install ejs --save
Enter fullscreen mode Exit fullscreen mode

Configure Express to use EJS:

app.set('view engine', 'ejs');
Enter fullscreen mode Exit fullscreen mode

Create an views folder and add an EJS file, e.g., home.ejs:

<!DOCTYPE html>
<html>
<head>
  <title>Express EJS</title>
</head>
<body>
  <h1><%= title %></h1>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

Render the EJS template:

app.get('/ejs-example', (req, res) => {
  res.render('home', { title: 'EJS Example' });
});
Enter fullscreen mode Exit fullscreen mode

7. Error Handling

Handle errors using middleware with four parameters (err, req, res, next). Add the following at the end of app.js:

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

8. API Endpoints

Create API endpoints that return JSON data:

app.get('/api/users', (req, res) => {
  const users = [{ id: 1, name: 'Alice' }, { id: 2, name: 'Bob' }];
  res.json(users);
});
Enter fullscreen mode Exit fullscreen mode

This concludes our Express.js tutorial with examples! Feel free to explore more features of Express and build amazing web applications.

Remember that this tutorial only scratches the surface of what Express.js can do. For more advanced topics, refer to the official Express.js documentation. Happy coding!

Top comments (0)