A
A
asergrisa2018-07-23 12:19:46
JavaScript
asergrisa, 2018-07-23 12:19:46

How to make 2 middleware work together?

I needed to write a middleware to check the size of the POST body, if it is greater than some value, return an error, otherwise go further.
I wrote this function:

function middleware(len = 10) {
  return (req, res, next) => {
    req.len = 0;
    req.on('data', function(chunk) {
      req.push(chunk);
      req.len += chunk.length;
      if (req.len > len) {
        res.write('Error');
        res.end();
      }
    });
    req.on('end', function() {
      if (req.len <= len) {
        next();
      }
    });
  };
}

app.use(middleware(10))
app.post('/',(req,res)=>{res.end('It works'))

Now if you run
curl http://host -d var=foo
Then it displays It works, and if you run
curl http://host -d var=SomeBigVar00000000000000000

it displays an error. Everything seems to be fine, but if you add `app.use(bodyParser.urlencoded());` between the first `app.use` and `app.post` to parse the body, then this middleware does not work.
How to make it work?

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