funerr
funerr

Reputation: 8166

How can I return html or json with Deno (oak)?

I've seen: How can I return html or json with deno? but I needed an answer for Oak - Posting below.

Upvotes: 7

Views: 2950

Answers (2)

yes
yes

Reputation: 261

Alternative Solution:

router.get('/test/', async (ctx) => {
    ctx.response.type = "application/json";
    ctx.response.body = {test: 1};
});

Upvotes: 1

funerr
funerr

Reputation: 8166

It would be something along the lines of:

import { Application } from 'https://deno.land/x/oak/mod.ts'
import { Router } from 'https://deno.land/x/oak/mod.ts'
const port = 8000

// Handler
const getTestResponse = ({ response }: { response: any }) => {
    response.status = 200
    response.headers.set("Content-Type", "application/json") // set to html if you want
    response.body = {
        data: "test"
    }
}

const app = new Application()

// Router
const router = new Router()
router.get('/api/v1/test', getTestResponse)
app.use(router.routes())
app.use(router.allowedMethods())

console.log(`Server running on port ${port}`)

await app.listen({ port })
  • Uses JSON by default for the response (no need to set explicitly like in the example) - I just wanted to show that you can change it.

Note: please split the handler, routes and the main code to different modules in the real world, so others won't be pissed at you :)

Upvotes: 3

Related Questions