Express is a fast, unopinionated, minimalist web framework for Node.js. It provides a robust set of features for web and mobile applications. This tutorial will guide you through the basics of setting up and using Express to create a simple web server.

Getting Started

To begin, you need to have Node.js installed on your system. You can download it from the official Node.js website.

Once Node.js is installed, you can create a new directory for your project and initialize a new Node.js application by running:

mkdir my-express-app
cd my-express-app
npm init -y

Now, install Express by running:

npm install express

Basic Server

Create a file named app.js in your project directory and add the following code:

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

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

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

Run your server with:

node app.js

Now, if you open your browser and navigate to http://localhost:3000, you should see "Hello, World!" displayed on the page.

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. They can be used to do things like logging, modifying the request and response objects, or terminating the request-response cycle.

Here's an example of a simple middleware function:

app.use((req, res, next) => {
  console.log(`${req.method} ${req.url}`);
  next();
});

This middleware will log every request's method and URL to the console.

Routing

Express allows you to define routes that map to specific functions. Here's an example of defining a route:

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

Now, if you navigate to http://localhost:3000/about, you should see "About Us" displayed on the page.

Templates

To render HTML templates, you can use templating engines like Pug or EJS. Install EJS by running:

npm install ejs

In your app.js, add the following code:

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

Create a file named about.ejs in a views directory and add the following code:

<!DOCTYPE html>
<html>
<head>
  <title>About Us</title>
</head>
<body>
  <h1>About Us</h1>
  <p>This is our about page.</p>
</body>
</html>

Now, modify the /about route to render the template:

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

Navigate to http://localhost:3000/about to see the rendered template.

Conclusion

This tutorial provides a basic overview of Express and how to use it to create a simple web server. For more detailed information, please visit our Node.js Express Documentation.


To learn more about Node.js, you can explore our Node.js Tutorials.