Route in Oak framework is defined in the same way as we do in Opine or in Express frameworks. In fact, all routes in Oak are defined by instantiating Router class in Oak framework.

 

// app.js

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

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

router.get('/', async (ctx) => {
  ctx.response.body = 'Web development with Oak framework.'
})

app.use(router.routes())
app.use(router.allowedMethods())

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

await app.listen({ port: 8000})

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

 

Route with parameter is defined as below:

 

// app.js

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

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

router.get('/post/:id', async (ctx) => {
  ctx.response.body = `The post id is: ${ctx.params.id}`
})

app.use(router.routes())
app.use(router.allowedMethods())

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

await app.listen({ port: 8000})

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

 

The mounting of the route is done as below:

 

// app.js

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

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

const index = new Router()
index.get('/', async (ctx) => {
  ctx.response.body = `Hello World!`
})

const login =  new Router()
login.get('/', async (ctx) => {
  ctx.response.body = `Welcome to login page!`
})

const router = new Router()
router.use('/', index.routes(), index.allowedMethods())
router.use("/login", login.routes(), login.allowedMethods())

app.use(router.routes())

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

await app.listen({ port: 8000})

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