DEV Community

Cover image for Basic Routing App in Deno using Oak
Haaris Iqubal for Recoding

Posted on • Updated on

Basic Routing App in Deno using Oak

Routing your Internet application is one of most important thing developer has to know about, Routing help use to keep our application safe as we can pass many authentication middleware, Routing also help our Internet application to have different pages for different purposes. Sometime implementing routing become more tedious job to implement if we want to use internal modules so how we will implement that let us think about!!! As Deno support Third Party module like Oak which will provide us a “application layer” as well as “routing layer”. With using these two classes we can implement our routing application. So without further ado let’s just do it. First of all we need to create our “app.ts” file our working directory will look like this.


-app.ts

Now we have to import our module we gonna use Oak so we will copy its link and write our import statement.

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

After importing our Application Class and Router Class we now need to initialize both of our module using following statement.


const app = new Application();

const router = new Router();

After initializing our router we can now setup what request we want to do with server and how will actually the router and what function they gonna provide. Request can be of many type like “GET”, “POST” ,“DELETE” etc…


router
  .get("/",(ctx) => {
   ctx.response.body = "Router has been created";
   // Implement your code
   })
  .post("/addPost", (ctx) => {
   ctx.response.body = "This is port request";
   // Implement your code   
   });

Our router has been setup now we have then these router path to our application, we can implement this by passing our router as a middleware to our application.

app.use(router.routes());

app.use(router.allowedMethods());

For the final step we just need to make our server listen to Port 8000 or any thing you want.


app.listen({port: 8000});

So this is how we can build a Deno Routing application pretty easily. Our final code will look this in app.ts file.

import { Application, Router } from "https://deno.land/x/oak/mod.ts";
const app = new Application();
const router = new Router();
router
  .get("/",(ctx) => {
   ctx.response.body = "Router has been created";
   // Implement your code
   })
  .post("/addPost", (ctx) => {
   ctx.response.body = "This is port request";
   // Implement your code   
   });
app.use(router.routes());
app.use(router.allowedMethods());;
app.listen({port: 8000});

So have fun with Deno and enjoy Deno with Oak 👍.

Alt Text

Top comments (1)

Collapse
 
ben profile image
Ben Halpern

Nice post!