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.