LOGBOOK

HELP

Quiz Entry - updated: 2026.10.28

What should an Express handler do with an incoming request body before processing it, and which status codes signal the two failure modes?

First read and parse the body, then validate it — answer 400 when the data fails validation, and 500 when an exception (like unparseable JSON) escapes.

Never trust what the client sent — anyone can call your API directly, bypassing your frontend and its validation entirely. The handler therefore runs a two-step gate:

  1. Read and parse — decode the raw body and run it through JSON.parse(). Malformed JSON throws right here.
  2. Validate — check that the parse produced the right shape: the expected fields exist, and their values are valid (correct type, within range).
router.post('/', (req, res) => {
  try {
    const body = JSON.parse(req.body.toString('utf-8'));
    if (body != null && 'option' in body
        && body.option >= 0 && body.option < responses.length) {
      // Process the request...
    } else {
      // The caller's data is wrong
      res.status(400).json({ error: 'invalid vote' });
    }
  } catch (error) {
    // An exception escaped (e.g. the body was not JSON)
    res.status(500).json({ error: 'server error' });
  }
});

The status-code convention: a request that reached validation but carries bad data is the caller's mistake → 400 Bad Request; an exception the server ran into → 500 Internal Server Error. Either way, report the failure with a status code instead of processing garbage.

Go deeper:

From Quiz: WEBT / Backend Integration | Updated: Oct 28, 2026