Reading Body

ServerRequest.body implements Deno.Reader and also provides handy parser methods for major content types.

  • body.text() parses UTF-8 decoded strings
  • body.json() try to parse body string as JSON
  • body.formData() try to parse if content-type is one of:
    • multipart/form-data
    • application/x-www-form-urlencoded
  • body.arryBuffer() returns full raw body as Uint8Array

// Copyright 2019 Yusuke Sakurai. All rights reserved. MIT license.
import { createRouter } from "https://servestjs.org/@v0.30.0/router.ts";
import { contentTypeFilter } from "https://servestjs.org/@v0.30.0/middleware.ts";
const router = createRouter();
router.post("/json", contentTypeFilter("application/json"), async req => {
  const bodyJson = (await req.body!.json()) as { name: string; id: string };
  // ...respond
});
router.post("/text", contentTypeFilter("text/plain"), async req => {
  const bodyText = await req.body!.text();
  // ...respond
});
router.post(
  "/multipart",
  contentTypeFilter("multipart/form-data"),
  async req => {
    const bodyForm = await req.body!.formData(req.headers);
    const name = bodyForm.field("name");
    const file = bodyForm.file("file");
    try {
      // ...respond
    } finally {
      // Clean up stored temp files
      await bodyForm.removeAllTempFiles();
    }
  }
);
router.post(
  "/form-urlencoded",
  contentTypeFilter("application/x-www-form-urlencoded"),
  async req => {
    const bodyForm = await req.body!.formData(req.headers);
    const name = bodyForm.field("name");
    const id = bodyForm.field("id");
    // ...respond
  }
);
router.post("/raw", async req => {
  const buf = await req.body!.arrayBuffer();
  // ...respond
});
// Start listening on port 8899
router.listen(":8899");