A voting backend receives GET /vote?option=1. What must the handler do before it responds with the updated results?
Validate first (does option exist and lie in the valid range?), then update the persisted count on the server, and only then respond — typically with the complete tally of all options as JSON.
* A vote's round trip: validate, update the stored count, answer with the full tally as JSON. *
Picture a small multiple-choice poll: the page shows four answer options, and clicking "vote" sends vote?option=N to the backend, which keeps one counter per option. A well-built handler works in three strictly ordered phases:
- Validate — is
optionpresent inreq.queryat all? Is its value inside the valid range (for four options: not< 0and not>= 4)? If either check fails, sendres.status(400)with an error message andreturnimmediately — the counters are never touched by bad input. - Process — convert the raw value with
parseInt()(query parameters always arrive as strings), read the stored count for that option, increment it, and write it back to server-side storage. - Respond — build an object with the counts of all options and send it as JSON, so the frontend can render the complete result, not just the one vote it cast.
The order is the security lesson: the early return on validation failure is what guarantees that nothing is ever written for a request like vote?option=99 or vote with no parameter at all.
Go deeper:
MDN: parseInt() — why query values need explicit conversion, and the radix gotcha.