Express.js / Express.js Basics

Basic Routing in Express.js

Routing is how Express.js applications respond to client requests. In this tutorial, you will learn how to define routes in Express and how to respond to different types of reques…

Tutorial 5 of 5 5 resources in this section

Section overview

5 resources

Covers the fundamental concepts of Express.js, including installation, setup, and creating a basic application.

1. Introduction

Goal of the Tutorial

This tutorial aims to provide an understanding of basic routing in Express.js. You will learn how to define different routes in Express and how to respond to various types of client requests.

Learning Outcomes

By the end of this tutorial, you will be able to:

  • Understand what routing in Express.js is
  • Define basic routes in Express.js
  • Handle different types of HTTP requests

Prerequisites

Before proceeding with this tutorial, you should have a basic understanding of Node.js and Express.js. Familiarity with JavaScript is also necessary.

2. Step-by-Step Guide

Basic Routing

Routing is a mechanism where HTTP requests are routed to the code that handles them. In Express.js, a route is a combination of a URL pattern and an HTTP method (get, post, put, delete, etc.), along with the code which should be executed when that route is matched.

Let's start with the most basic route in Express.js:

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

In the above code, app.get() is used to define a route. The first parameter is a string that represents the URL pattern. The second parameter is a callback function that will be executed if a GET request is made to the root URL ('/').

Handling Different Types of Requests

Express.js can handle different types of HTTP requests. Let's add a POST route:

app.post('/', function(req, res) {
  res.send('Got a POST request')
})

3. Code Examples

Example 1: GET and POST Requests

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

// Handle GET request
app.get('/', (req, res) => res.send('Handling GET request'))

// Handle POST request
app.post('/', (req, res) => res.send('Handling POST request'))

app.listen(port, () => console.log(`Example app listening at http://localhost:${port}`))

In this example, when you navigate to 'http://localhost:3000', you will receive the message 'Handling GET request'. If you send a POST request to the same URL, you will receive 'Handling POST request'.

4. Summary

You've learned the basics of routing in Express.js, including how to handle different types of HTTP requests. Next, you could learn about more advanced routing concepts, such as route parameters and middleware.

5. Practice Exercises

  1. Create an Express.js server that responds with "Hello, User!" to a GET request at '/user'.

  2. Extend the above server to respond with "Creating a new user..." to a POST request at '/user'.

  3. Further extend the server to respond with "Updating the user..." to a PUT request at '/user'.

Here are the solutions:

// Exercise 1
app.get('/user', function(req, res) {
  res.send('Hello, User!')
})

// Exercise 2
app.post('/user', function(req, res) {
  res.send('Creating a new user...')
})

// Exercise 3
app.put('/user', function(req, res) {
  res.send('Updating the user...')
})

These exercises should help you get a better understanding of how routing works in Express.js. Keep practicing with different routes and request methods to solidify your understanding.

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

Countdown Timer Generator

Create customizable countdown timers for websites.

Use tool

Random Name Generator

Generate realistic names with customizable options.

Use tool

JavaScript Minifier & Beautifier

Minify or beautify JavaScript code.

Use tool

Color Palette Generator

Generate color palettes from images.

Use tool

Percentage Calculator

Easily calculate percentages, discounts, and more.

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