简体   繁体   中英

How to terminate node.js http request if size is too large?

I want to terminate an http server in node.js process if the user's request is larger than 8mb. My current code appears to work in basic testing but I'm not sure if res.end() is async and could be destroyed before completion by process.exit(). I used process.exit here because if the user's request is larger than 8mb I don't want to have to keep the process alive while they send large amounts of data.

req.on('data', (chunk) => {
    body += chunk;
    if(body.length > 8000000) {
        res.writeHead(413, defaultHead);
        res.end('{"error":"Request exceeded 8mb maximum size."}');
        process.exit(0);
    }
});

The way you are doing, it will work because same thing is done by body-parser the popular package for parsing req.body in express.

Now, How body-parser does is, it uses another package called raw-body , which takes a limit parameter and if the current chunk > limit it calls the callback that is passed.

  function onData (chunk) {
    if (complete) return

    received += chunk.length

    if (limit !== null && received > limit) {
      done(createError(413, 'request entity too large', {
        limit: limit,
        received: received,
        type: 'entity.too.large'
      }))
    } else if (decoder) {
      buffer += decoder.write(chunk)
    } else {
      buffer.push(chunk)
    }
  }

done is the callback here, and it creates an error and pushes it as the first param in the callback.

In the body-parser code:

getBody(stream, opts, function (error, body) {
  if (error) {
    var _error= createError(400, error)

    // read off entire request
    stream.resume()
    onFinished(req, function onfinished () {
      next(createError(400, _error))
    })
    return
  }

  ....
  next()
})

In case of error, It just reads off the entire stream using stream.resume() and passes the error. So basically you are replicating a simple version of this, which in theory should work.

Note, onFinished is another package which Execute a callback when a HTTP request closes, finishes, or errors.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM