Share On: Twitter Facebook Google+ LinkedIn Pinterest Tumblr Reddit

Node.js express route management

Tags: nodejs routing

route management in nodejs

In the article, there is information about the route management of the express module , which is used to manage requests to the web server with Node.js.

Route in Express is a middle layer like static that comes with the express module to manage requests to the web server .

Express uses the Router feature to manage incoming requests flexibly and regularly.

The following codes can be used for the router feature.


'use strict';

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

The Router property takes as a parameter an object containing the caseSensitive, mergeParams, and strict properties.

The caseSensitive parameter indicates that the /homepage and /homepage addresses are the same.

The mergeParams parameter is used to avoid parameter conflicts from multiple address management / routes.

The strict parameter provides strict address management, that is, the /home and /home/ addresses are the same.

Managing requests with the router


    'use strict';

    const express = require('express');
    const app = express();
    const router = express.Router();
    
    router.get('/', function (req, res) {
    
      res.send('Hello Express');
      //res.send('

Hello Express

'); }); router.post('/', function (req, res) { res.send('Hello Express'); }); app.use('/', router); app.listen(8000, function () { console.log('Server running...'); });

The important thing to note here is to determine in which directory the Router will be active with the use method

If the first parameter of the method is changed to /user , the Router will now work for requests to the /user directory.

Express module get, post, put, head, delete, options, trace, copy, lock, mkcol, move, purge, propfind, proppatch, unlock, report, mkactivity, checkout, merge, m-search, notify, subscribe, unsubscribe, Supports patch, search and connect methods.


    'use strict';

    const express = require('express');
    const app = express();
    const router = express.Router();
    
    router.get('/', function (req, res) {
      res.send('User Operations');
    });
    
    router.post('/', function (req, res) {
      res.send('User Operations POST request');
    });
    
    router.put('/', function (req, res) {
      res.send('User Operations PUT request');
    });
    
    router.delete('/', function (req, res) {
      res.send('User Operations DELETE request');
    });
    
    app.use('/user', router);
    
    app.listen(8000, function () {
      console.log('Server running...');
    });

In the example , User actions will respond to get requests to the /user directory , User actions will respond to post requests as POST requests, put requests will be PUT requests to User actions, and user actions will respond to delete requests as DELETE requests.

NOTE: HTTP methods (get, post, put, delete etc.) are used for different operations.

The GET method is used to call the page, the POST method is used to save the data, the PUT method is used to update the data, and the DELETE method is used to delete the data.

In addition, the complexity can be reduced by writing more than one method in order with the route method in the Router.


    'use strict';

    const express = require('express');
    const app = express();
    const router = express.Router();
    
    router.route('/')
      .get(function (req, res) {
        res.send('User Operations');
      })
      .post(function (req, res) {
        res.send('User Operations POST request');
      })
      .put(function (req, res) {
        res.send('User Operations PUT request');
      })
      .delete(function (req, res) {
        res.send('User Operations DELETE request');
      });
    
    app.use('/user', router);
    
    app.listen(8000, function () {
      console.log('Server running...');
    });

With the all method in the router, a function can be written that will work in all HTTP methods.


    'use strict';

    const express = require('express');
    const app = express();
    const router = express.Router();
    
    router.route('/')
      .all(function (req, res, next) {
        console.log('A new login');
        next();
      })
      .get(function (req, res) {
        res.send('User Operations');
      })
      .post(function (req, res) {
        res.send('User Operations POST request');
      })
      .put(function (req, res) {
        res.send('User Operations PUT request');
      })
      .delete(function (req, res) {
        res.send('User Operations DELETE request');
      });
    
    app.use('/user', router);
    
    app.listen(8000, function () {
      console.log('server running...');
    });

Web pages usually consist of more than one section.

By creating more than one Router, different answers can be given for different sections.


    'use strict';

    const express = require('express');
    const app = express();
    const user = express.Router();
    const site = express.Router();
    
    user.get('/', function (req, res) {
      res.send('users');
    });
    
    user.get('/login', function (req, res) {
      res.send('Login place');
    });
    
    user.get('/registration', function (req, res) {
      res.send('registration place');
    });
    
    site.get('/', function (req, res) {
      res.send('homepage');
    });
    
    site.get('/communication', function (req, res) {
      res.send('communication');
    });
    
    app.use('/', site);
    app.use('/user', user);
    
    app.listen(8000, function () {
      console.log('Server running...');
    });

The server will run the rules written to the site Router for / and /communication , and to the user Router for /user , /user/login and /user/registration .

However, proliferating rules cause the codes to become more complex.

In this case, writing different Router modules for different sections will make the code easier to edit.

Save the following codes as user.js.


    'use strict';

    const express = require('express');
    const app = express();
    const user = express.Router();
    
    user.get('/', function (req, res) {
        res.send('users');
    });
    
    user.get('/login', function (req, res) {
        res.send('Login place');
    });
    
    user.get('/registration', function (req, res) {
        res.send('registration place');
    });
    
    module.exports = user;

Save the following codes as site.js.


    'use strict';

    const express = require('express');
    const app = express();
    const site = express.Router();
    
    site.get('/', function (req, res) {
      res.send('homepage');
    });
    
    site.get('/communication', function (req, res) {
      res.send('communication');
    });
    
    module.exports = site;

Write and run the following codes in a file in the same folder as user.js and site.js.


    'use strict';

    const express = require('express');
    const app = express();
    const user = require('./user');
    const site = require('./site');
    
    app.use('/', site);
    app.use('/user', user);
    
    app.listen(8000, function () {
      console.log('server running...');
    });

It can be used in the following codes to reduce the written codes.


    'use strict';

    const express = require('express');
    const app = express();
    
    app.use('/', require('./site'));
    app.use('/user', require('./user'));
    
    app.listen(8000, function () {
      console.log('server running...');
    });

You can edit and use the codes according to yourself for reducing the written codes and for a more understandable code layout.

Addresses with user information on web pages are usually specified with a special number or user name.

Instead of defining a different rule for each user, we can use the regular expression feature in the express module.


    'use strict';

    const express = require('express');
    const app = express();
    const user = express.Router();
    
    user.get('/:name', function (req, res) {
      res.send('Hello ' + req.params.name);
    });
    
    app.use('/user', user);
    
    app.listen(8000, function () {
      console.log('server running...');
    });

With the /:name rule written , the server became able to respond to /user/**name** requests.

Anything (/user/yusuf, /user/sefa, /user/sezer etc.) can be written in the **name** field here .

The sent user information (yusuf, sefa, sezer, etc.) is named as a parameter.

After the parameters are sent, the method named param in express runs.

Using this method, the information of the sent parameter can be searched in the database or different operations can be performed.


    'use strict';

    const express = require('express');
    const app = express();
    const user = express.Router();
    const users = [
      {
        username: 'spiderman',
        name: 'peter',
        surname: 'parker'
      },
      {
        username: 'ironman',
        name: 'tony',
        surname: 'stark'
      }
    ];
    
    let IsExist = false;
    
    user.param('name', function (req, res, next, name) {
    
      users.forEach(function (exist) {
    
        if (exist.username == name) IsExist = true;
    
      }, this);
    
      next();
    
    });
    
    user.get('/:name', function (req, res) {
    
      if (IsExist) res.send('The user is exist.');
    
      res.end('The user is not exist.');
    
      IsExist = false;
    
    });
    
    app.use('/user', user);
    
    app.listen(8000, function () {
      console.log('Server is running...');
    });

Sometimes it is desired that the parameters sent are only numbers, in this case, a regular expression that only accepts numbers should be written.


    'use strict';

    const express = require('express');
    const app = express();
    const user = express.Router();
    
    user.get('/:id(\\d+)', function (req, res) {
      res.send('Hello');
    });
    
    app.use('/user', user);
    
    app.listen(8000, function () {
      console.log('Server is running...');
    });

In the example; The **id** value in the expression /user/**id** will only get numbers.

E.g; It will not work for a value like /user/yusuf or /user/1yusuf but will work for a value like /user/123456.

Similarly, for special requests, rules that only work for the desired state can be written by writing a custom regular expression.

It may be requested to give the same response/page to all requests to some sections.

For such a process, it will be sufficient to add an asterisk (*) to the first parameter of the relevant http method (get, post, etc.).


    'use strict';

    const express = require('express');
    const app = express();
    const user = express.Router();
    
    user.get('*', function (req, res) {
      res.send('Please login!');
    });
    
    app.use('/user', user);
    
    app.listen(8000, function () {
      console.log('Server is running...');
    });

In the example /user, /user/login, /user/info/login/12 etc. requests will be given the same reply/page.

I wish you a good day.

Comments(0)