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

2

7

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

Stank answered 22/8, 2020 at 17:24 Comment(0)
S
3

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 :)

Stank answered 22/8, 2020 at 17:24 Comment(1)
I had the same problem. response.headers.set("Content-Type", "text/html") was the missing piece of the puzzle - thanks very much!Sula
P
1

Alternative Solution:

router.get('/test/', async (ctx) => {
    ctx.response.type = "application/json";
    ctx.response.body = {test: 1};
});
Palatial answered 26/3, 2022 at 14:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.