Languages
[Edit]
EN

Node.js / Express.js - routers

0 points
Created by:
Krzysiek
351

In this article, we would like to show you how to use routers in Express.js.

Introduction

Normally, we define routes in Express.js using the following syntax:

app.httpMethod(path, handler);

Where:

  • httpMethod is one of the following requests:
    • GET
    • POST
    • PUT
    • PATCH
    • DELETE
  • path is the route at which the request will run.

Practical example:

const express = require('express');

const app = express();

app.get('/users', (req, res) => {
  res.send('Welcome to the users page!');
});

app.listen(5000);

Now, when we run the application and go to the localhost:5000/users we get the following result:

Node.js / Express.js - HTTP GET method example result
Node.js / Express.js - HTTP GET method example result

We can also define multiple different methods (such as GET, POST... ) for the same route.

Example:

const express = require('express');

const app = express();

app.get('/users', (req, res) => {
  res.send('Welcome to the users page!');
});

app.post('/users', (req, res) => {
    // ...
    res.send('User created successfully');
  });
  
app.listen(5000);

To easy maintain the application we need to separate the routes dedicated for users from our main index.js file. To do so we will use express.Router.

Routers

1. The first thing we need to do is create a new directory called routes and a file for our users routes - users.js. The project structure should now look as follows:

project/
        ├─ node_modules/
        └─ routes/
			  └─ users.js
        ├─ index.js
        ├─ package.json
        └─ package-lock.json

2. Inside the users.js file, import express.Router and move the users requests from index.js to it.

users.js file:

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

// routes from index.js
router.get('/', (req, res) => {
  res.send('Welcome to the users page!');
});

router.post('/', (req, res) => {
  // ...
  res.send('User created successfully');
});

//export this router to use it in index.js
module.exports = router;

Note:

Notice that now we use router instead of app and we don't write '/users' in the request path. We will specify it later in the index.js file.

3. Import the router inside index.js file and specify the route.

const express = require('express');

const app = express();

// import the router
const users = require('./routes/users.js');

// specify the route '/users' for '/' in users.js file
app.use('/users', users);

app.listen(5000);

Now the app.use() function call on route '/users' attaches the users router with this route. Whatever requests our app gets at the '/users', will be handled by our users.js router. The '/' route in users.js file is actually a subroute of '/users'.

Run the app and go to the http://localhost:5000/users to see the result.

Result:

Node.js / Express.js - result for HTTP GET method using express.Router
Node.js / Express.js - result for HTTP GET method using express.Router
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join