Route with Oak in Deno
About creating advanced routes in Deno
In our base app tutorial we have seen how to create default page for our app. It is not a route, it's middle-ware. In this example we create some basic routes using oak Router and add it as middle ware using the use method.
Oak routes
We can create Oak router for our app in the same file. But as the application develop, the code become large, so in order to make it simple and easy to handle we keep routes in separate file and later include them as middle-ware to the main application.
In a folder called routes create a file route.ts
import { Router } from "https://deno.land/x/oak/mod.ts"; const router = new Router() router.get('/', (ctx) => { ctx.response.body = 'Home Page' ctx.response.status = 200 }) router.get('/about', (ctx) => { ctx.response.body = 'About Page' ctx.response.status = 200 }) router.get('/products', (ctx) => { ctx.response.body = 'Products Page' ctx.response.status = 200 }) export default router;
In the first line we import the Router from the Oak module, which is used to create our basic site routes. Then we export the router and will call the routers in the main.ts as follows.
Here '/' route is the default page / index page of our app.
Arrow function
//main.ts import { Application } from "https://deno.land/x/oak/mod.ts"; import router from './routes/route.ts' const app = new Application(); app.use(router.routes()) app.use((ctx) => { ctx.response.body = "Not found"; }); app.listen({ port: 8000 }); console.log('Server running on port 8000')
In the main.ts we added the route as middle ware, lets run the app with net permission.
deno run --allow-net main.ts
Now jump into the browser access your route http://127.0.0.1/.
To stop the running server use Ctrl+C
All of my Deno projects will be published on my GitHub Repo, so keep watching.
Comments