Express.js / Routing in Express.js

Basic Routing

In this tutorial, we will cover the basics of routing in Express.js. We will learn how to define routes, create route handlers, and send responses back to the client.

Tutorial 1 of 4 4 resources in this section

Section overview

4 resources

Explores handling routes, route parameters, and query strings in Express applications.

Introduction

Welcome to this tutorial where we will learn the basics of routing in Express.js. Our goal is to understand how to define routes, create route handlers and send responses back to the client.

By the end of this tutorial, you will be able to:
- Understand what is routing in Express.js.
- Define and handle different routes.
- Send responses back to the client.

Before we start, make sure you have the following prerequisites:
- Basic knowledge of JavaScript.
- Node.js and npm installed on your system.
- Basic understanding of how Express.js works.

Step-by-Step Guide

What is Routing?

Routing refers to how an application's endpoints (URIs) respond to client requests. In Express.js, routing takes the following structure: app.Method(Path, Handler), where:
- app is an instance of express.
- Method is an HTTP request method, in lowercase.
- Path is a path on the server.
- Handler is the function executed when the route is matched.

Defining Routes

To define a route, we use app.Method(), replacing Method with the HTTP method we want to respond to. For example, to respond to GET requests, we would use app.get().

Creating Route Handlers

A route handler is the function that gets executed when a route is matched. It takes the request and response objects as parameters. The request object (req) represents the HTTP request and has properties for the request query string, parameters, body, HTTP headers, etc. The response object (res) is used to send data back to the client in response to the request.

Code Examples

Example 1: Basic GET Request

Here's an example of a basic GET request to the home page ("/").

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

// Define a route handler for GET requests to the home page
app.get('/', function(req, res) {
  res.send('Hello, world!');
});

app.listen(3000, function() {
  console.log('App is listening on port 3000');
});

In the above example, we first import Express.js and create an app. We then define a route handler for GET requests to the home page ("/"). If a client sends a GET request to our server's home page, they will receive the response 'Hello, world!'. Finally, we start our server on port 3000.

Summary

In this tutorial, we learned the basics of routing in Express.js. We learned how to define routes, create route handlers, and send responses back to the client.

For further learning, you might consider exploring more complex route patterns, middleware, or how to handle POST requests.

Here are some additional resources:
- Express.js Routing Guide
- MDN Web Docs on HTTP Methods

Practice Exercises

  1. Define a route handler for GET requests to "/about" that responds with 'About Us'.
  2. Define a route handler for GET requests to "/contact" that responds with 'Contact Us'.

Solutions:
1. javascript app.get('/about', function(req, res) { res.send('About Us'); });
2. javascript app.get('/contact', function(req, res) { res.send('Contact Us'); });

Keep practicing with different routes and responses. Try adding more HTTP methods to your repertoire. Happy coding!

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

Meta Tag Analyzer

Analyze and generate meta tags for SEO.

Use tool

Random String Generator

Generate random alphanumeric strings for API keys or unique IDs.

Use tool

WHOIS Lookup Tool

Get domain and IP details with WHOIS lookup.

Use tool

AES Encryption/Decryption

Encrypt and decrypt text using AES encryption.

Use tool

Text Diff Checker

Compare two pieces of text to find differences.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help