R
R
romaro2021-09-24 01:51:34
JavaScript
romaro, 2021-09-24 01:51:34

How to apply middleware inside another middleware?

Using Express and I want to use different parsers depending on the MIME type. But I don't understand how I can apply this parser inside the middleware. I try with case:multipart and expect that a new route will be added to the current express instance and applied after exiting the middleware using the next() method. Why doesn't Express apply the new handler?

import express from 'express';
import multer from 'multer';

const formParser = multer();
const jsonParser = express.json();

export default class {
    get handler() {
        return (req, res, next) => {
            console.log('Боди-парсер');

            switch (req.is(['urlencoded', 'json', 'multipart'])) {
                case 'urlencoded':
                    // parse urlencoded body
                    throw new Error('implement urlencoded body parsing')
                case 'json':
                    // parse json body
                    throw new Error('implement json body parsing')
                case 'multipart':
                    // parse multipart body
                    //throw new Error('implement multipart body parsing')
                    req.app.post('*', formParser.none());
                    next();
                    break;
                default:
                    // 415 error code
                    res.statusCode = 415
                    res.end()
                    break
            }
        }
    }
}

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question