Routes in Express

Routes in Express

Yesterday while I was studying express docs, I came across on how to make different route paths, so thought of sharing them with you folks.

1. The usual one: We use this one generally but for this you have to be exactly the same as the one coded and no property can be dynamic.

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

app.get('/products', (res, req) => {
res.send("product page");
})

2. Conditional One: When a letter from the path name is conditional to be present, this is done by adding a question mark ahead of that letter.

app.get('/ab?cd', (req, res) => {
    res.send("abcd or acd");
})

3. When route path can have any number of that character : This means that one particular char can occur any number of time in the route path , it just has to be accompanied with a '+' sign ahead of it.

app.get('/ab+cd', (req, res) => {
    res.send("abbbbbbbbbbbbbbbbbbcd  or abcd or abbbbcd ...");
})

4. Fixed pattern at start and at end: At times when we can have our route to be having a fixed pattern on the start and end of the route.

app.get('/ab*cd', (req, res) => {
    res.send("ab6484s84ads46ad65dcd");
})

5. Having a regex in the starting : When you have regex in the starting of you route , than this can be managed by enclosing that regex between back-slashes.

app.get(/a/, (req, res) => {
    res.send("a ke baad kuch bhi koi farak nahi padta :)");
})

6. A particular pattern in the route : You can also modify your regex to find a particular pattern in between the whole route, for this just add a star before that regex and a dollar sign after it, meanwhile closing it with back-slashes.

app.get(/.*fly$/, (req, res) => {
    res.send("let us fly");
})

7. When you want a part of your route dynamic : This is the most used one, when lets say you have a part of your route which indicates the id of a product and remaining quantity in inventory ; the dynamic value is followed by a colon ':'

app.get('/users/:userID/books/:booksID', (req, res) => {
    console.log(req.query);
    res.send(req.params); 
// will give us dynamic parameters and there value on the page 
})

These are the different ways by which you can form a route and a facilitate tasks from your backend application.

For further read, you can visit Official Docs

Thanks for reading the blog, I hope you enjoyed it and learnt something cool.

Share your thoughts with me , by connecting on Twitter or LinedIn

Until Next time => Ciao() ;