CWright
CWright

Reputation: 2098

Koa pass data from server to client

I want to pass through some environment variables from a Koa server to the client. In express I could do something like res.render('index', { data: 'someData' }); and then I could access data. In Koa I can't see how to do this. It mentions using context.state but I can't find any example of how to retrieve this in the client.

Upvotes: 0

Views: 1172

Answers (1)

Saad
Saad

Reputation: 53799

You can do something similar in Koa, you just need to use the right middleware. Try out koa-views if you're using one of the supported engines.

Here is a full example (this example assumes you're using Koa v1 and EJS as your templating engine):

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: 'ejs' }))
app.use(router.routes())
app.use(router.allowedMethods())

app.listen(3000)

routes.js

const router = require('koa-router')()

router.get('/', function * () {
  yield this.render('index', { title: 'Home' })
})

router.get('/about', function * () {
  yield this.render('about', { title: 'About' })
})

module.exports = router

Just change the extension argument you pass to the middleware based on which templating engine you are using.

Upvotes: 1

Related Questions