[Hapi.js] Managing State with Cookies

hapi has built-in support for parsing cookies from a request headers, and writing cookies to a response, making state management easy and straight-forward. It even has built in support for cookie encryption and auto detects when a cookie contains JSON, parsing or stringifying automatically.

'use strict'
const Hapi = require('hapi')
const server = new Hapi.Server()
server.connection({ port: 8000 })

// set default cookie
server.state('hello', {
  ttl: 60 * 60 * 1000,  // expiry time
  isHttpOnly: true,
  encoding: 'iron',
  password: 'a5LewP10pXNbWUdYQakUfVlk1jUVuLuUU6E1WEE302k'
})

server.route({
  method: 'GET',
  path: '/',
  config: {
    handler: function(request, reply) {
      // read cookie
      let hello = request.state.hello
      reply(`Cookies! ${hello}`)
        .state('hello', 'world') // set cookie
    }
  }
})

server.start(() => console.log(`Started at: ${server.info.uri}`))
原文地址:https://www.cnblogs.com/Answer1215/p/5229555.html