I've seen: How can I return html or json with deno? but I needed an answer for Oak - Posting below.
Asked
Active
Viewed 2,088 times
2 Answers
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 :)

funerr
- 7,212
- 14
- 81
- 129
-
1I had the same problem. `response.headers.set("Content-Type", "text/html")` was the missing piece of the puzzle - thanks very much! – Rounin Feb 28 '21 at 09:59
1
Alternative Solution:
router.get('/test/', async (ctx) => {
ctx.response.type = "application/json";
ctx.response.body = {test: 1};
});

yes
- 241
- 2
- 11