AppDividend
Latest Code Tutorials

Express Router Tutorial Example From Scratch

508

Get real time updates directly on you device, subscribe now.

Express Router Tutorial Example From Scratch is today’s leading topic. Routing refers to how an application’s endpoints (URIs) respond to client requests. Express is the popular Node.js web framework. Amongst its functionality as it provides a wrapper for Routing. The Express Router class helps in the creation of route handlers. Express apps utilize routers that are essentially containers for a set of middleware. We can put this middleware holder only on a specific route, which allows us to keep our logic in separate files and bring them together on our terms.

Earn a Tech Degree and get the skills like Frontend Development or Javascript Development that can help you to launch a career. Join the program

Express Router Tutorial Example From Scratch

First of all, we will create a project for the express router example tutorial.

#1: Create an express project.

Create one project folder and go inside that folder.

mkdir erouter && cd erouter

Now, initialize the package.json file using the following command.

npm init -y

 

Express Router Tutorial Example From Scratch

Now, install the express using the following command.

npm install express --save

# or

yarn add express

#2: Let us write the first express route.

Now, inside the root folder. Create one file called server.js and add the following code.

// server.js

const express = require("express");
const app = express();
const PORT = process.env.PORT = 3000;

let router = express.Router();

router.get('/',function(req,res){
  res.json({'message' : 'Ping Successfull'});
});

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

app.listen(PORT,function(){
  console.log('Server is running at PORT:',PORT);
});

First, we have imported all the required modules and then create an object of a router and then defined on the root route. Then we have used the middleware saying that, if any request comes with the ‘/api’ then it will call the router function with its route. So in our case, we will get a JSON response.

So this was the example of basic routing that we used to do when we create a web application with express on Node.js platform.

#Route Methods

Express supports the main following routing methods.

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

There are still other methods, but mainly we used the above methods in a web application. There is a routing method called app.all() which is not derived from any HTTP method. The routing method gets loaded for functions at a specified path for all of the request methods.

The route path is used to define an endpoint where requests can be made. It is like a backend endpoint.  In the Express, route paths can be string patterns or regular expressions.

In the above example, the route path is the below.

// server.js

router.get('/',function(req,res){
  res.json({'message' : 'Ping Successfull'});
});

Here, the router path is “/.”

The route parameters are used to capture the values that are specified to a particular position in the URL. They are called the URL segments. The values obtained are made available in a req.params object, using the name of the route parameter specified in the path as the keys of the values.

Route parameter is significant in functionality like edit, update, and delete. We generally pass the ID on the parameter and extract from the request. The syntax is like this.

Related Posts
1 of 17
http://localhost:3000/api/user/:id

Now, at Express Router, we can access the ID using the following code.

http://localhost:3000/api/user/1

In the req.params, the following will be available: { “id”: “1” }

So, we can access the 1 using the following code.

req.params.id

#Express Route POST Request

The basic syntax of express post route is the following.

// server.js

router.post('/', function(req, res){
   res.send('It's a post route, grab the data and save in the Mongo');
});

Inside the router post method, we save the data that come from req and extract that data from req and save the data inside the database.

Just like the following code.

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

So, here we have used the Mongoose model to save the data in the MongoDB database. It is just a real-time example that will show you how you can create your post request and save the data in the database.

#Router-level middleware

Router-level middleware works in the same way as application-level middleware, except it is bound to an instance of express.Router().

// server.js

const app = express();
const router = express.Router();

router.use(function (req, res, next) {
  console.log('Time:', Date.now());
  next();
});

router.use('/user/:id', function (req, res, next) {
  console.log('Request URL:', req.originalUrl);
  next();
}, function (req, res, next) {
  console.log('Request Type:', req.method);
  next();
});

Finally, Express Router Tutorial Example From Scratch is over.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.