I am looking to migrate my Express app to Koa but I have no idea how to get the route and template working in Koa. It seems that there is documentation about this on their official site.
For instance this is how I would do it in Express:
var express = require('express');
var app = express();
// respond with "Hello World!" on the homepage
app.get('/', function (req, res) {
res.send('Hello World!');
});
// accept POST request on the homepage
app.post('/', function (req, res) {
res.send('Got a POST request');
});
// accept PUT request at /user
app.put('/user', function (req, res) {
res.send('Got a PUT request at /user');
});
// accept DELETE request at /user
app.delete('/user', function (req, res) {
res.send('Got a DELETE request at /user');
})
How is this done in Koa then? What I get from their doc:
const Koa = require('koa');
const app = new Koa();
app.use(async ctx => {
ctx.body = 'Hello World';
});
app.listen(3000);
Also, when comes to the template rendering, in Express:
var express = require('express');
var router = express.Router();
router.get("/make", function(req, res) {
return res.render("streams/make", {...});
});
So, how is this done in Koa?
Any ideas?
As mentioned already by Joe, Koa doesn't come with any middleware preinstalled.
For your needs, it seems like you would want to look into using koa-router
and koa-views
.
Usage:
app.js
const Koa = require('koa')
const views = require('koa-views')
const router = require('./routes')
const app = new Koa()
app.use(views(`${__dirname}/views`, { extension: 'pug' })) // You can replace 'pug' with whatever templating engine you're using.
app.use(router.routes())
app.use(router.allowedMethods())
app.listen(3000)
module.exports = app
routes.js
const Router = require('koa-router')
const router = new Router()
router.get('/', async ctx => {
ctx.body = 'Hello World!'
})
// accept POST request on the homepage
router.post('/', async ctx => {
ctx.body = 'Got a POST request'
})
// accept PUT request at /user
router.put('/user', async ctx => {
ctx.body = 'Got a PUT request at /user'
})
// accept DELETE request at /user
router.delete('/user', async ctx => {
ctx.body = 'Got a DELETE request at /user'
})
// Render a template
router.get("/make", async ctx => {
await ctx.render("streams/make", { ... });
})
module.exports = router
With Koa, instead of getting the req
and res
as parameters, you just get a ctx
. With this ctx
object, you can access the request via ctx.request
and the response with ctx.response
. ctx.body
is just an alias for ctx.response.body
. Koa defines a lot of aliases for you, which you can read about here.