Express JS Router

Express JS Router

Create routes using the Express JS Router

In this chapter, you will learn about the express js router. Basically, It is used to creating routes.


Getting started

So go to your desktop and create a new folder and name it as you wish. This is our app folder.

Then go inside the app folder(express route) and here initialize the npm by executing the npm init command.

After initializing the npm now install express.js. To install express run npm install express --save command on your terminal.

Make sure that your app folder is selected on your terminal.


Files creation

Inside the app folder, we will create two files one is index.js file and another routes.js.


routes.js

To create routes we will use express.Router. The express.Router class is used to create modular, mountable route handlers.

Note: A Router instance is a complete middleware and routing system.

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

router.get('/', (req, res) => {
    res.send('<h1>Home Page</h1>');
});

router.get('/about', (req, res) => {
    res.send('<h1>About Page</h1>');
});

module.exports = router;

index.js

Now in the index.js we will be importing routes and applying as a middleware.

const express = require('express');
const app = express();
// IMPORT ROUTES
const routes = require('./routes');
// Applying as Middleware
app.use(routes);

app.listen(3000, () => console.log('Your app listening on port 3000'));

http://localhost:3000/

Browser Output
Home Page

http://localhost:3000/about

Browser Output
About Page

Tip:1

app.use('/api',routes);

http://localhost:3000/api/

Browser Output
Home Page

http://localhost:3000/api/about

Browser Output
About Page

Tip:2

In all the above examples, you have to notice that –

http://localhost:3000/about/
&
http://localhost:3000/about

Both work the same. But, you can avoid that by enabling the router’s strict mode.

Enable router strict mode –

const router = express.Router({strict:true});

Next isRetrieve Post Data Using Express JS

Previous is – Express JS Route Handler

Posts Navigation


Leave a Reply

Your email address will not be published. Required fields are marked *