I've seen: How can I return html or json with deno? but I needed an answer for Oak - Posting below.
How can I return html or json with Deno (oak)?
Asked Answered
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 :)
Alternative Solution:
router.get('/test/', async (ctx) => {
ctx.response.type = "application/json";
ctx.response.body = {test: 1};
});
© 2022 - 2024 — McMap. All rights reserved.
response.headers.set("Content-Type", "text/html")
was the missing piece of the puzzle - thanks very much! – Sula