用koa-session这个包却获取不到ctx.session的值
发布于 7 年前 作者 coderzzp 7605 次浏览 来自 问答

用koa2写接口,我在登陆成功的接口里写了类似如下代码

exports.signIn = async (ctx, next) => { //如果登陆成功 ctx.session.user=’…’ }

但是接下来我在另一个接口中却获取不到ctx.session这个值,中间件的使用方式以及options都与官网一致,看样子也是支持koa2的

const session = require(‘koa-session’); const Koa = require(‘koa’); const app = new Koa();

app.keys = [‘some secret hurr’];

const CONFIG = { key: ‘koa:sess’, /** (string) cookie key (default is koa:sess) / /* (number || ‘session’) maxAge in ms (default is 1 days) / /* ‘session’ will result in a cookie that expires when session/browser is closed / /* Warning: If a session cookie is stolen, this cookie will never expire / maxAge: 86400000, overwrite: true, /* (boolean) can overwrite or not (default true) / httpOnly: true, /* (boolean) httpOnly or not (default true) / signed: true, /* (boolean) signed or not (default true) / rolling: false, /* (boolean) Force a session identifier cookie to be set on every response. The expiration is reset to the original maxAge, resetting the expiration countdown. (default is false) / renew: false, /* (boolean) renew session when session is nearly expired, so we can always keep user logged in. (default is false)*/ };

app.use(session(CONFIG, app)); // or if you prefer all default config, just use => app.use(session(app));

环境如下:

“node”: "8.9.3" “koa”: “^2.2.0”, “koa-session”: “^5.0.0”

请问是哪里出了问题么

12 回复
import convert from 'koa-convert';

app.use(convert(session({
  store: redisStore,
  prefix: 'kails:sess:',
  maxAge: 24 * 60 * 60 * 1000, //one day in ms,
  key: 'kails.sid'
})))

koa-convert你可能需要用这个转一下

@18820227745 这个我测试过了,应该不是koa版本的问题

@coderzzp

convert(session({
  store: redisStore,
  prefix: 'kails:sess:',
  maxAge: 24 * 60 * 60 * 1000, //one day in ms,
  key: 'kails.sid'
}))

convert转换一下session中间件也不行吗

代码不全,感觉不是你发的这块代码的问题

@zhhb 上传到github上了 https://github.com/coderzzp/koa2-sever ,在目录app/controllers/user.js里面

请求是否带了cookie 没有带cookie是取不到session的

@moyunchen 问题出在这cookie这了,跨域请求默认不允许发送cookie,必须设置

http://50linesofco.de/post/2017-03-06-cors-a-guided-tour 这篇也很好的解释了CORS跨域请求中遇到的cookie问题

@coderzzp 就是这样的。cookies是作为session存储的key. 我感觉

回到顶部