Last active
August 23, 2024 22:14
-
-
Save tsibley/7afc8fc6cfa8591c84a7f3a3b78438f5 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import express from 'express'; | |
const app = express(); | |
// Middleware to parse req.body from application/x-www-form-urlencoded to an object | |
app.use(express.urlencoded({ extended: false })); | |
// Shared state that the server has access to. Could be a database or some | |
// other external service. | |
let counter = 0; | |
app.route("/counter") | |
.get((req, res) => res.send(` | |
The counter is at: ${counter}. | |
<form method="post"> | |
<label> | |
Add <input type="number" name="n" value="1"> to counter | |
</label> | |
<input type="submit" value="do it"> | |
</form> | |
`)) | |
.post((req, res) => { | |
const n = Number(req.body.n); | |
// Validation, authz, etc. | |
if (!Number.isFinite(n)) | |
return res.status(400).send("Bad Request: not a number"); | |
counter += n; | |
// Could also render again directly here and send it without | |
// redirect, but best practice is redirect POST → GET. | |
return res.redirect("/counter"); | |
}); | |
app.listen(3000) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment