Any typical application is bound to have multiple routes. Each of these routes usually serve a particular functionality. Routes can also correspond to different pages. In this post, we are going to implement ExpressJS route handlers. Also, we will learn how to parse request body for these route handlers.

If you are new to Express, check out this post on creating an ExpressJS application.

1 – ExpressJS Route Handlers

We can implement ExpressJS route handlers using the app.use() function.

For example, suppose our application has two routes – the root page and an about page. We can handle the routes as below:

const express = require('express');

const app = express();

app.use('/about', (req, res, next) => {
    res.send('<h1>The About Page</h1>')
})

app.use('/', (req, res, next) => {
    res.send('<h1>Hello from Express</h1>')
})

app.listen(3000)

Generally, we utilize app.use() function for adding a middleware to the Express app context. However, this function is overloaded. In other words, we can also use it with a slightly different signature.

In the above example, the app.use() function receives a string value along with the callback function. The string value is basically the route path. Here, we implement one handler for the root path i.e. / and another handler for the /about path.

Important point to note is that /about handler should be declared before the root path. This is because the root handler will catch all path values starting with /. If the root handler is the first handler in the chain, no other path handlers will work.

2 – ExpressJS Request Body Parsing

Next, we move on to the important topic of parsing an ExpressJS request body for a particular route handler.

To demonstrate the same, let us create a simple endpoint that presents a form to the user to enter a message. When the user enters a message and submits the form, our application will show a different page with the message.

To start with we need to install a special package known as body-parser.

$ npm install --save body-parser

Now, let us implement the route handler for the message form. See below:

app.use('/send-message', (req, res, next) => {
    res.send('<form action="/message" method="POST"><input type="text" name="message"><button type="submit">Send</button></form>')
})

Basically, we will display the form when the user visits the /send-message route. The form action will take us to /message and a POST request will be made. The form itself has only one input field and a button for submission.

Next, we can implement the request handler for /message route. Check out the complete code for the same.

const express = require('express');
const bodyParser = require('body-parser')

const app = express();

app.use(bodyParser.urlencoded({extended: false}));

app.use('/about', (req, res, next) => {
    res.send('<h1>The About Page</h1>')
})

app.use('/send-message', (req, res, next) => {
    res.send('<form action="/message" method="POST"><input type="text" name="message"><button type="submit">Send</button></form>')
})

app.use('/message', (req, res, next) => {
    console.log(req.body);
    res.send(`<h1>Message Received: ${req.body.message}</h1>`)
})

app.use('/', (req, res, next) => {
    res.send('<h1>Hello from Express</h1>')
})

app.listen(3000)

As you can see, we first import the body-parser object. Then, we add the bodyParser.urlencoded() as a middleware function using app.use(). Also, we set the extended property as false to prevent a deprecation warning.

Now, we can deal with request body in our application.

Basically, in the handler for /message route, we extract the message property from req.body object and display it in the browser page.

Conclusion

With this, we have successfully implemented ExpressJS route handlers and also looked at how to parse the request body. This opens up the scope of our application complexity as we can now have multiple routes for different functionality.

Want to organize multiple routes effectively? Check out this post on ExpressJS Router Middleware.

If you have any comments or queries about this post, please feel free to mention them in the comments section below.


Saurabh Dashora

Saurabh is a Software Architect with over 12 years of experience. He has worked on large-scale distributed systems across various domains and organizations. He is also a passionate Technical Writer and loves sharing knowledge in the community.

0 Comments

Leave a Reply

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