DEV Community

Cover image for Routing in Expressjs
Naftali Murgor
Naftali Murgor

Posted on

4 1

Routing in Expressjs

Introduction

Routing refers to how an application’s endpoints (URIs) respond to client requests. Expressjs official Docs

You define routing using express app object corresponding HTTP methods POST and GET method.

For example

The following code shows an example of a very basic route.

const express = require('express')
const app = express() // express object

// respond with "hello world" when a GET request is made to the homepage
app.get('/', function (req, res) {
  res.send('hello world')
})
Enter fullscreen mode Exit fullscreen mode

Route Methods

A route method is derived from one of the HTTP methods and is attached and called on app object, an instance of the express class.

GET and POST Methods to the root off the app:

// GET method route
app.get('/', function (req, res) {
  res.send('GET request to the homepage')
})

// POST method route
app.post('/', function (req, res) {
  res.send('POST request to the homepage')
})

Enter fullscreen mode Exit fullscreen mode

Route Paths

These routes defined in the above code snippet will map to:
http://localhost:3000/ when app is run locally and matching depends on whether client uses POST or GET method and vice versa.

// GET method route
app.get('/about', function (req, res) {
  res.send('about route')
})
// 
Enter fullscreen mode Exit fullscreen mode

The above route matches to http://localhost:3000/about when the app is run locally.


Summary

We've learn't how to define routes in a very basic approach. In the next article, we shall learn about Route Params

Image of Datadog

The Essential Toolkit for Front-end Developers

Take a user-centric approach to front-end monitoring that evolves alongside increasingly complex frameworks and single-page applications.

Get The Kit

Top comments (0)

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay