You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.
// 导入 User 模型,用于操作 users 表数据
const User = require ( '../models/User' ) ;
// 核心:登录接口逻辑
const login = async ( req , res ) => {
try {
// 1. 检查请求体是否存在
if ( ! req . body ) {
return res . status ( 400 ) . json ( {
code : 400 ,
msg : '请求体不能为空'
} ) ;
}
// 2. 从前端请求体中获取登录参数(用户名、密码)
const { username , password } = req . body ;
// 3. 验证参数是否完整(基础校验,避免空值请求)
if ( ! username || ! password ) {
return res . status ( 400 ) . json ( {
code : 400 ,
msg : '用户名和密码不能为空'
} ) ;
}
// 3. 从数据库中查询该用户名对应的用户( Sequelize 方法,无需手写 SQL)
const user = await User . findOne ( {
where : { username : username } // 条件:用户名匹配
} ) ;
// 4. 判断用户是否存在
if ( ! user ) {
return res . status ( 401 ) . json ( {
code : 401 ,
msg : '用户名不存在'
} ) ;
}
// 5. 比对密码(当前入门阶段用明文比对,后续可优化加密)
if ( user . password !== password ) {
return res . status ( 401 ) . json ( {
code : 401 ,
msg : '密码错误'
} ) ;
}
// 6. 登录成功:返回用户信息(隐藏密码,避免泄露)
const { password : _ , ... userInfo } = user . dataValues ; // 解构删除密码字段
return res . status ( 200 ) . json ( {
code : 200 ,
msg : '登录成功' ,
data : userInfo // 返回用户ID、用户名、邮箱等安全信息
} ) ;
} catch ( error ) {
// 7. 捕获异常(如数据库错误)
return res . status ( 500 ) . json ( {
code : 500 ,
msg : '登录失败,服务器异常' ,
error : error . message
} ) ;
}
} ;
// 导出登录方法,供路由调用
module . exports = { login } ;