koa 是一個(gè)中間件框架,本身并不能處理 session,在 koa 中處理 session 需要其他中間件的支持。本文用 koa-session-minimal 做 session 處理的中間件,其他處理 session 的中間件大同小異。
項(xiàng)目目錄結(jié)構(gòu)
$ find .
.
./app.js
./config.js
./routes.js
代碼
app.js
const Koa = require('koa')
const app = new Koa()
require('./config')(app)
require('./routes')(app)
app.listen(3000)
config.js
const bodyParser = require('koa-bodyparser')
const session = require('koa-session-minimal')
module.exports = app => {
// 應(yīng)用解析請(qǐng)求體的中間件, koa-bodyparser 支持 json, form, text 類(lèi)型的請(qǐng)求體
app.use(bodyParser())
// 應(yīng)用處理 session 的中間件
app.use(session({
key: 'session-id', // cookie 中存儲(chǔ) session-id 時(shí)的鍵名, 默認(rèn)為 koa:sess
cookie: { // 與 cookie 相關(guān)的配置
domain: 'localhost', // 寫(xiě) cookie 所在的域名
path: '/', // 寫(xiě) cookie 所在的路徑
maxAge: 1000 * 30, // cookie 有效時(shí)長(zhǎng)
httpOnly: true, // 是否只用于 http 請(qǐng)求中獲取
overwrite: false // 是否允許重寫(xiě)
}
}))
}
routes.js
const Router = require('koa-router')()
// 模擬數(shù)據(jù)庫(kù), 存儲(chǔ)用戶(hù)信息
const users = new Map([['laowang', {username: 'laowang', password: '123456'}]])
// 默認(rèn)提示信息
const tips = `
GET / 查看登錄信息
POST / {username: laowang; password: 123456} 發(fā)此請(qǐng)求以登錄
DELETE / 注銷(xiāo)
`
module.exports = app => {
// 查看登錄信息
Router.get('/', ctx => {
// 查看 session 中是否有用戶(hù)登錄信息
if (ctx.session.user) {
ctx.body = {
status: '您已登錄',
session: ctx.session.user
}
} else {
ctx.body = tips
}
})
// 登錄
Router.post('/', ctx => {
// 從請(qǐng)求體中獲取用戶(hù)名和密碼
const { username, password } = ctx.request.body
// 檢查用戶(hù)是否已經(jīng)登錄
if (ctx.session.user) {
ctx.body = `${ctx.session.user.username} 已登錄,請(qǐng)勿重復(fù)登錄`
}
// 從'數(shù)據(jù)庫(kù)'中查找是否有此用戶(hù),有則繼續(xù)判斷密碼是否正確
else if (users.has(username)) {
// 模擬從數(shù)據(jù)庫(kù)查找用戶(hù)的操作
const user = users.get(username)
// 判斷用戶(hù)名和密碼是否正確
if (username === user.username && password === user.password) {
// 驗(yàn)證通過(guò)則將用戶(hù)信息寫(xiě)入 session 中
ctx.session.user = {
username,
password
}
ctx.body = '登陸成功,請(qǐng)?jiān)L問(wèn) GET / 查看session中的信息'
} else {
ctx.body = '用戶(hù)名或密碼不正確'
}
} else {
ctx.body = '用戶(hù)不存在'
}
})
// 注銷(xiāo)
Router.del('/', ctx => {
ctx.session = null
ctx.body = '您已注銷(xiāo)'
})
// 處理未匹配到的路由
Router.get('/*', ctx => {
ctx.body = tips
})
app.use(Router.routes())
}
測(cè)試

測(cè)試 GET 請(qǐng)求

設(shè)置 Content-Type

測(cè)試 POST 請(qǐng)求

登錄后查看 session 中的信息

測(cè)試 DELETE 請(qǐng)求