Reputation: 8166
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
Reputation: 261
Alternative Solution:
router.get('/test/', async (ctx) => {
ctx.response.type = "application/json";
ctx.response.body = {test: 1};
});
Upvotes: 1
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 })
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