Saving Data to a Database
Reading is only half the story. Let's handle form submissions so users can write data to your database. The pattern is always the same: read the body, validate, insert, respond.
A POST endpoint reads form fields from the request body:
POST "/messages" :\n string content = req.body("content")\n string author = req.body("author")\n if content == ""\n return http.respond(400, "text/plain", "Content is required")\n string params = "[\\"" + author + "\\", \\"" + content + "\\"]"\n db.query("INSERT INTO messages (author, content) VALUES (?, ?)", params)\n return http.respond(201, "text/plain", "Message saved!")POST /messages (with form data) → 201 Message saved!\nPOST /messages (empty content) → 400 Content is requiredreq.body("field") reads a form field from the POST body. Validate before inserting — return 400 for bad input. Return 201 Created when a new resource is successfully created. The params order must match the ? placeholder order in your SQL.
A complete route pair: GET shows a form, POST handles it:
GET "/messages/new" :\n html:\n <form method="post" action="/messages">\n <input name="author" placeholder="Your name">\n <textarea name="content" placeholder="Message"></textarea>\n <button type="submit">Send</button>\n </form>\n\n POST "/messages" :\n string content = req.body("content")\n string author = req.body("author")\n if content == ""\n return http.respond(400, "text/plain", "Content is required")\n string params = "[\\"" + author + "\\", \\"" + content + "\\"]"\n db.query("INSERT INTO messages (author, content) VALUES (?, ?)", params)\n return http.respond(200, "text/html", "<p>Saved! <a href='/messages/new'>Send another</a></p>")GET /messages/new → HTML form\nPOST /messages → 200, confirmation messageGET shows the form, POST processes it. This GET-POST pair is the foundation of every web form. In production you'd redirect after POST to prevent double-submission, but this pattern is the right starting point.
Quick recap
- POST endpoints use req.body("fieldname") to read submitted form fields
- Validate input before writing to the database — return 400 for invalid data
- 201 Created is the conventional status for a successfully created resource
- Build params as a JSON array — values must match ? placeholder order