R
R
romaro2021-04-13 22:08:12
Express.js
romaro, 2021-04-13 22:08:12

How to move the middleware chain from the route to the controller?

The problem grows from the fact that I don't fully understand how Express chains work.

The project has a route that properly processes post requests:

const express = require('express');
const router = express.Router();
const jsonParser = express.json();
const controller = require('../controllers/regController');

router.post('/', jsonParser, function (req, res) {
    if (!req.body) return res.sendStatus(400);
    console.log(req.body);
    res.json(
        {
            serverErr: '',
            fieldsErr: {
                username: 'Тест',
            }
        }
    );
})

module.exports = router;


I take out the logic for processing this route in the controller. To do this, I leave in regRouter.js: And from regController.js I export the function:
router.post('/', jsonParser, controller.register);

module.exports.register = function (req, res) {
    if (!req.body) return res.sendStatus(400);
    console.log(req.body);
    res.json(
        {
            serverErr: '',
            fieldsErr: {
                username: 'Тест',
            }
        }
    );
})


This option also works, but how can I put jsonParser into the controller as well? Or is it like the top-level middlware should always stay in the block and precede "custom" route handlers?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
StiflerProger, 2021-04-13
@romaro

const express = require('express');
const jsonParser = express.json();

module.exports.register = [jsonParser, function (req, res) {
    if (!req.body) return res.sendStatus(400);
    console.log(req.body);
    res.json(
        {
            serverErr: '',
            fieldsErr: {
                username: 'Тест',
            }
        }
    );
})]

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

const controller = require('../controllers/regController');

router.post('/',  controller.register)

module.exports = router;

Like this is how it should look. Correct me if I'm wrong)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question