The request object contains data from the user when he/she clicks something on the frontend or backend to get some kind of information in exchange. The information about user request is wrapped in the request object before sending to the middleware responsible to handle it.

 

In the request object, there is a method called body( ) that “returns a representation of the request body. When no options are passed, the request headers are used to determine the type of the body, which will be parsed and returned. The returned object contains two properties," stated the team developing Oak framework on their GitHub.

 

According to the team, the property “type” could contain the following value: "json", "text", "form", "form-data", "bytes" or "undefined". And we can use this type property to request the body to be returned in a particular format.

 

The team added: “Because of the nature of how the body is parsed, once the body is requested and returned in a particular format, it can't be requested in certain other ones, and .request.body() will throw if an incompatible type is requested.”

 

// app.js

import { Application, Router } from "https://deno.land/x/oak/mod.ts"
import html from "./views/index.jsx"

const app = new Application({keys: ["secret1"]})
const router = new Router()

router.get('/', async (ctx) => {
  ctx.response.body = html
})

router.post('/form', async (ctx) => {
  const body = ctx.request.body({ type: "form" });
  const value = await body.value
  ctx.response.body = value.get('username')
})
 
app.use(router.routes())
app.use(router.allowedMethods())

app.use(async (context, next) => {
  try {
    await context.send({
      root: `${Deno.cwd()}/static`,
      index: "index.html",
    });
  } catch {
    await next()
  }
})

app.addEventListener(
  "listen",
  (e) => console.log("Listening on http://localhost:8000")
)

await app.listen({ port: 8000})

// denon run --allow-net --allow-read app.js

 

// views/index.jsx

/** @jsx h */
import { h, renderSSR } from "https://deno.land/x/nano_jsx@v0.0.33/mod.ts"

function Index(props){
  return(
    <html>
      <head>
        <meta charset="UTF-8"/>
        <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
        <title>Oak Web Framework</title>
      </head>
      <body>
        <form action="/form" method="post" >
          <input type="text" name="username" placeholder="Enter your name" />
          <input type="submit" value="Submit" />
        </form>
      </body>
    </html>
  )
}

const message = 'Web development with Oak framework'
const str = renderSSR(<Index message={message} />)
const html = `<!DOCTYPE html>${str}`

export default html