简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM