May 22, 2024

express.Router() Function With Examples

In the post ExpressJS Routing With Examples we have already seen how to set up basic routing in ExpressJS. In this post we'll see how to use express.Router() function to create modular route definitions.

The Router instance you get by calling express.Router() function is a complete middleware and routing system on its own. It helps you to create modular route definitions meaning you can create route definitions in separate files and export it. Later you can import the router module in the file where it is needed. Let's see it with the help of an example.

express.Router() example

In the code there is a GET method route which sends a form as response with method as 'POST'. This request should be called first.

Once you have the form and you click the submit button that triggers the post request.

This example uses body-parser package which is used to parse the request body as we want to extract the entered name from the request.

Create a separate routes folder to keep all the route definitions, with in this folder create a file named route.js and write the routes there.

route.js

const express = require('express');

const router = express.Router();

router.get('/hello', (req, res) => {
    res.send('<form action="/name" method="post"><input type="text" name="name"><button type="submit">Submit</button></form>');
})

router.post('/name', (req, res) => {
    console.log(req.body.name);
    const name = req.body.name;
    res.send('<h3>Your name is ' + name + '</h3>');
})

module.exports = router;

Important points about the code.

  1. express.Router() function is used to create a new router object.
  2. Once you’ve created a router object, you can add middleware and HTTP method routes (such as get, put, post, and so on) to it. In the code router.get() and router.post() are used.
  3. Router object is exported using module.exports() so that it can be used in other files.

With that a modular route definition is ready. You can use it in any other file.

Importing modular routes created using express.Router()

We'll import the route definitions in a file named app.js.

app.js

const express = require('express');
const appRoutes = require('./routes/route');
const bodyParser = require('body-parser'); 
const app = express();
const port = 3000;

app.use(bodyParser.urlencoded({extended: true}));
// routes
app.use(appRoutes);
//Server
app.listen(port, () => {
    console.log(`Example app listening on port ${port}`)
})

Important points about the code.

  1. Route definition file is imported by giving the relative path of the file.
    const appRoutes = require('./routes/route');
    
  2. Using app.use() method you can mount the specified middleware function so app.use() is used to mount the route definitions.
  3. With that your app will now be able to handle requests to /hello and /name that are specified in route module.

You can run the application using the following command

node app.js

Example app listening on port 3000

If you go to the URL http://localhost:3000/hello, server gets a GET request for the path ('/hello') and executes the callback function which sends the form as response.

Express routing

Enter a name and press submit which should send a POST request to the server. In the callback function name is extracted from the parsed request body and a response is sent to the user.

That's all for the topic express.Router() Function With Examples. If something is missing or you have something to share about the topic please write a comment.


You may also like

No comments:

Post a Comment