// router/user.js
const {SuccessModel,ErrorModel} = require('../model/resModel')
const {login} = require('../controller/user')
const {set} = require('../db/redis')
const handelUserRouter = (req,res) => {
const method = req.method // GET POST
// 登录(api/user/login)
if(method === "GET" && req.path === "/api/user/login"){
const {username,password} = req.query
const result = login(username,password)
return result.then(data=>{
if(data.username){
console.log('data ===>'+ data)
// 设置session
req.session.username = data.username
req.session.realname = data.realname
// 同步到redis中,将session放到redis中与sessionId关联起来
set(req.sessionId,req.session)
return new SuccessModel()
}
return new ErrorModel('登录失败')
})
}
// 登录验证测试
if(method === "GET" && req.path === '/api/user/login-test'){
if(req.session.username){
return Promise.resolve(
new SuccessModel({
session: req.session
})
)
}
return Promise.resolve(
new ErrorModel('登录失败'))
}
}
module.exports = handelUserRouter
// controller/user.js
const {exec} = require('../db/mysql')
const login = (username,password) => {
const sql = `select username,realname from users where username='${username}' and password='${password}'`
return exec(sql).then(rows => {
return rows[0] || {}
})
}
module.exports = {
login
}
使用redis之前可以获取到data,使用redis后就获取不到data了,找不到原因,请老师帮忙看一下问题出在哪里