koa 基础(十六)koa 中 session 的使用

1.app.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
/**
 * koa 中 session 的使用
 * 1、npm install koa-session --save
 * 2、const session = require('koa-session');
 * 3、app.keys = ['some secret hurr'];
 * const CONFIG = {
 *   key: 'koa:sess',
 *   maxAge: 86400000,
 *   overwrite: true,
 *   httpOnly: true,
 *   signed: true,
 *   rolling: false,
 *   renew: false
 * }
 *
 * 4、设置 session
 * ctx.session.username = '张三';
 * 5、获取 session
 * ctx.session.username
 */
// 引入模块
const Koa = require('koa');
const router = require('koa-router')(); /*引入是实例化路由 推荐*/
const render = require('koa-art-template');
const path = require('path');
const session = require('koa-session');
 
// 实例化
let app = new Koa();
 
// 配置 koa-art-template 模板引擎
render(app, {
  root: path.join(__dirname, 'views'), // 视图的位置
  extname: '.html', // 后缀名
  debug: process.env.NODE_ENV !== 'production' // 是否开启调试模式
})
 
// 配置session的中间件
app.keys = ['some secret hurr']; /** cookie的签名 */
const CONFIG = {
  key: 'koa:sess', /** 默认 */
  maxAge: 86400000, /** cookie的过期时间 【需要修改】*/
  overwrite: true, /** (boolean) can overwrite or not (default true) 没有效果 默认*/
  httpOnly: true, /** true表示只有服务器端可以获取cookie*/
  signed: true, /** 默认 签名 */
  rolling: false, /** 在每次请求时强行设置 cookie,这将重置 cookie 过期时间(默认:false) 【需要修改】*/
  renew: true, /** (boolean) renew session when session is nearly expired 【需要修改】*/
}
app.use(session(CONFIG, app));
 
router.get('/', async (ctx) => {
  // 获取session
  console.log(ctx.session.userinfo);
  await ctx.render('index', {
    list: {
      name: '张三'
    }
  });
})
 
router.get('/news', async (ctx) => {
  // 获取session
  console.log(ctx.session.userinfo);
  ctx.body = '新闻页面';
})
 
router.get('/login', async (ctx) => {
  // 设置session
  ctx.session.userinfo = '张三';
  ctx.body = '登录成功';
})
 
app.use(router.routes());
app.use(router.allowedMethods());
 
app.listen(3000);

.

posted @   每天都要进步一点点  阅读(1160)  评论(0编辑  收藏  举报
编辑推荐:
· dotnet 源代码生成器分析器入门
· ASP.NET Core 模型验证消息的本地化新姿势
· 对象命名为何需要避免'-er'和'-or'后缀
· SQL Server如何跟踪自动统计信息更新?
· AI与.NET技术实操系列:使用Catalyst进行自然语言处理
阅读排行:
· dotnet 源代码生成器分析器入门
· 官方的 MCP C# SDK:csharp-sdk
· 一款 .NET 开源、功能强大的远程连接管理工具,支持 RDP、VNC、SSH 等多种主流协议!
· 一文搞懂MCP协议与Function Call的区别
· 一次Java后端服务间歇性响应慢的问题排查记录
历史上的今天:
2018-05-24 react 实现pure render的时候,bind(this)隐患
2017-05-24 ionic2
点击右上角即可分享
微信分享提示