Open fengyuanzemin opened 5 years ago
@fengyuanzemin the code you posted here works fine.
I suspect that the middleware that threw the error ctx.session.isNew undefined
was used before the koa session middleware was used and the order of your middleware matters when you use a custom store.
The following will not work as expected.
const sessions = {}
const CONFIG = {
store: {
async get(key) {
return sessions[key]
}
, async set(key, value) {
sessions[key] = value
}
, async destroy(key) {
sessions[key] = null
}
}
}
app.use(async context => {
console.log(context.session)
})
app.use(session(CONFIG, app))
You must use the session middleware first.
app.use(session(CONFIG, app))
app.use(async (context, next) => {
console.log(context.session)
})
I have the same "issue". isNew
is true
on the first call, but undefined
on all subsequent calls (once I set some data inside the session object)
import Koa from 'koa'
import BodyParser from 'koa-bodyparser'
const cors = require('@koa/cors')
const bodyParser = require('koa-bodyparser')
const session = require('koa-session')
const app = new Koa()
app.use(cors({
credentials: true
}))
app.use(bodyParser())
app.keys = ['somekey']
app.use(session(app))
app.use(ctx => {
console.log(ctx.session.isNew)
ctx.session.foo = 'bar'
ctx.status = 200
})
const port = 3000
app
.use(BodyParser())
.listen(port)
.on('listening', () => {
console.log(`Listening on port ${port}...`)
})
I have a client-side app on port 8080, sending POST requests with axios.
import axios from 'axios'
export const http = axios.create({
withCredentials: true,
baseURL: 'http://localhost:3000'
})
Example
dependencies
index.js