An Interest In:
Web News this Week
- March 21, 2024
- March 20, 2024
- March 19, 2024
- March 18, 2024
- March 17, 2024
- March 16, 2024
- March 15, 2024
Routing in Expressjs
Introduction
Routing refers to how an applications 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 homepageapp.get('/', function (req, res) { res.send('hello world')})
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 routeapp.get('/', function (req, res) { res.send('GET request to the homepage')})// POST method routeapp.post('/', function (req, res) { res.send('POST request to the homepage')})
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 routeapp.get('/about', function (req, res) { res.send('about route')})//
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
Original Link: https://dev.to/naftalimurgor/routing-in-expressjs-3o53
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To