How do I create an Express Router?

·

2 min read

Express Router

As normally we do, create an Express application on your main JS file.

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



app.listen(3000, () => {
    console.log('Serving app on localhost 3000')
})

Now, suppose we have a folder called routes which has a file called shelter.js

to set a route object, require express on your shelter.js file and then create a router with express. More info express.Route()

const express = require('express');
const router = express.Router();

router.get('/shelters', (req, res) => {
    res.send("All Shelters")
})

router.post('shelters', (req, res) => {
    res.send("Creating Shelter")
})

router.get('/shelters/:id', (req, res) => {
    res.send("Viewing one Shelter")
})

router.get('/shelters/:id/edit', (req, res) => {
    res.send("Edit One Shelter ")
})

module.exports = router;

then, require it on your main js file and use it

const shelterRoute = require('./routes/shelters)

app.use('/', shelterRoutes);

Do you remember, we set the routes under the name of shelters?

We can change and set them only with "/" without specifying the name of our routes.

Let's take a look at our shelter.js file to see how we changed them

router.get('/', (req, res) => {
    res.send("All Shelters")
})

router.post('/', (req, res) => {
    res.send("Creating Shelter")
})

router.get('/:id', (req, res) => {
    res.send("Viewing one Shelter")
})

router.get('/:id/edit', (req, res) => {
    res.send("Edit One Shelter ")
})

With this, we can just rename our route in only one place, which means if I decided its name is barkers or whatever name you may need, this can be done from your main.js file and will work on your browser path as well.

app.use('/barkers', shelterRoutes);

app.use('/pointers', shelterRoutes);

I'm sharing my process while taking my course on Udemy. To know more about it, go to the next link. The Web Developer Bootcamp 2021