node.js – Routes in separate files

Question:

How do I put routes in separate files?

var express = require('express');
var App = express.Router();
var Notas = require('../api/notas');

App.route('/notas')
    .get(Notas.read)
    .post(Notas.create);

App.route('/notas/:id')
    .get(Notas.profile)
    .put(Notas.update)
    .delete(Notas.delete);

Is it good to separate the routes?

Answer:

You can separate routes by file. To do this, create a new Router in the new file and reference it in your main route file:

app.js

const express = require('express');
const app = express.Router();
const notas = require('../api/notas');

app.use('/notas', notas);

notas.js

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

const get = async (req, res) => {
  res.jsonp({ mensagem: 'OK' });
}

router.get('/', get);

module.exports = router;

Router

A router object is an isolated instance of middleware and routes. You can think of it as a "mini-application", capable only of performing middleware and routing functions. Every Express application has a built-in router app.

In free translation:

A router object is an isolated instance of middleware and routes. You can think of it as a "mini application", only capable of performing middleware and routing functions. Every Express application has an integrated application router.

Scroll to Top