How the Express Router function works

Asked

Viewed 663 times

3

To use a middleware in Express, I do as the code below:

var express = require('express');
var app = express();

app.use('/', function(req, res, next) { 
    console.log('Middleware!');
});

However, I realized that it is also possible to do this:

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

var app = express();

router.get('/', function(req, res, next) {
    res.send('Index!');
});

router.get('/teste', function(req, res, next) {
    res.send('Teste!');
});

app.use('/', router);

How does the Router function work? What does it do under the cloths?

1 answer

1

express. Router() is a Nodejs route manager/handler. It serves to create routes in a modularized way, thus making it possible to create a separate file of route manipulation.

For example, create a directory called "Rotes" and create an "indexRotes.js" file. Inside this file you will use Router() to create a route structures that will soon be exported.

indexRotas.js

const express = require('express')
const router = express.Router() //chamei de router mas poderia ser qualquer outro nome

router.use((req, res, next) => {...})

router.get('/', (req, res) => {...})

router.get('/home', (req, res) => {...})

router.get('/login', (req, res) => {...})
router.post('/login', (req, res) => {...})

//404
router.use((req, res) => {
    res.send('404: Page not found')
})

module.exports = router

Notice I used the Router() to create several routes and at the end I exported it. Now in the archive apps js. I can care you.

app js.

//IMPORTS EXTERNAL   
const express = require('express')
const app = express()

//IMPORTS INTERNAL
const routes = require('./rotes/indexRotes') //importando o roteador

//SERVER CONFIG
app.use(...)
app.use(...)
app.listen(...)

//ROUTES
app.use('/', routes)

Okay, now you have a separate file that specifically takes care of your routes, with direct to middleware and more, in a large application can contain hundreds of routes, so it is more interesting a modular router that takes care of just that.

Tip: recommend you declare the next only when using it, so keep the code cleaner and no unnecessary information.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.