Express Router

Rubleen Kaur
Last Updated: May 13, 2022

Introduction

Express.js is a free and open-source backend web framework for Node.js. Node.js is a runtime environment used to execute JavaScript code outside of a browser. It is used to produce dynamic web page content before sending it to the user's web browser. The Express Router class is used to create modular, mountable route handlers. An Express Router instance is a complete middleware and routing system; hence it is often referred to as a “mini-app.”Express Router is a built-in class that specifies how the application’s endpoints respond to the client requests. The express router class can further help in the creation of the route handlers. 

 

Let’s see a basic example for the same:

 

Install the express module in Node using the given command:

 

npm install express --save

or

yarn add express

 

Now, inside the root folder, create a server.js file and add the given code.

 

const express = require('express')
const app = express()
const port = 3000

app.get('/', (req, res) => {
  res.send('Hello World!')
})

app.listen(port, () => {
  console.log(`Ninja's app listening at http://localhost:${port}`)
})


OUTPUT

 

 

Express Router Methods

Express supports the listed main routing methods:

  1. GET
  2. POST
  3. PUT
  4. HEAD 
  5. DELETE
  6. OPTIONS

 

The routing method gets loaded for functions at a specified path for all of the request methods.

Route Paths 

The route path is used to define the endpoints from where the requests can be made—the route path functions as a backend endpoint. In Express, the route path can be either string patterns or regular expressions. In the above example, the route path used is ‘/.’ 
 

app.get('/'(req, res) => {
  res.send('Hello World!')
})

 

 

Route Parameters

In Express, the route parameters are variables that are derived from the named section of the URL. Route parameters have specific properties that reduce the amount of validation that is required to perform versus using query parameters or request bodies: 

  • A routing parameter can never be null or undefined. Let's consider an example if a request to GET /users above will cause an HTTP 404, and this will not call the route handler for /users/:userId/books/:bookId.
  •  A routing parameter is always a string that has a positive length. For example, GET /user/42/books/ also causes an HTTP 404. 

If we define an HTTP API in Express, it is usually better to make a route parameter rather than a query parameter or a body parameter if possible. If your parameter is mandatory and doesn't need to be an object, route parameters are generally the way to go.

 

Express Router POST Request

The basic syntax of Express Router POST request is given by - 
 

// server.js

router.post('/'function(req, res){
  res.send('It's a post route, which grabs the data');
});

 

In the router post method, data is saved from the req, and we can extract that data from the req and save the data inside a database.

 

router.route('/ninja').post(function (req, res) {
  let model = new Model(req.body);
  model.save()
    .then(game => {
    res.status(200).json({'model''Your class data is saved'});
    })
    .catch(err => {
    res.status(400).send("unable to save to database");
    });
});

 

In the above example, We have used the Mongoose model to save the data in the MongoDB database. A real-time example shows us how we can create our post requests and keep our data in the database. 

 

Frequently Asked Questions

  1. What is Express?
    Answer: Express is a small framework. It sits on top of Node.js as web server functionality to simplify its APIs and add more helpful new features. 
     
  2. What is an Express Router?
    Answer: The Express Router class is used to create modular, mountable route handlers. An Express Router instance is a complete middleware and routing system; hence it is often referred to as a “mini-app”.
     
  3. What is middleware?
    Answer: The middleware gets executed before our routes get invoked. There are many possible usages for using Middleware for routes, such as to log every request before it’s invoked or find out whether the request is proper or not.

 

Key Takeaways

Hey everyone, so let’s brief out the article. Let’s discuss in brief whatever we have discussed here. 

  •  In this article, we have briefed about what is an express router, the various available express router methods, and then we have discussed the Routing Paths. Express Router is a built-in class that specifies how the application’s endpoints respond to the client requests. The express router class can further help in the creation of the route handlers. 

     
  • We have discussed the various Route Parameters and what is the Express Router POST Request. The route parameters are variables that are derived from the named section of the URL. Route parameters have specific properties that reduce the amount of validation required to perform versus using query parameters or request bodies.

     

Isn’t Web Development engaging? Building new websites and using amazing animations and different APIs, don’t be scared if you cannot grasp the hold of this vast development. We have the perfect web development course for you to make you stand out from your fellow developers. 

 

Happy Learning Ninjas!

 

Was this article helpful ?
0 upvotes