// 导入必要的模块
const express = require('express');
const router = express.Router();
const { body, validationResult } = require('express-validator');
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const User = require('../models/user');
 
// 注册接口
router.post('/register', 
  [
    body('username').isLength({ min: 5 }).withMessage('用户名至少5个字符'),
    body('password').isLength({ min: 5 }).withMessage('密码至少5个字符'),
    body('email').isEmail().withMessage('请输入有效的邮箱')
  ], 
  async (req, res) => {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({ errors: errors.array() });
    }
 
    const { username, password, email } = req.body;
 
    try {
      // 检查用户是否已存在
      const userExists = await User.findOne({ username });
      if (userExists) {
        return res.status(400).json({ message: '用户已存在' });
      }
 
      // 创建新用户
      const user = new User({
        username,
        password: bcrypt.hashSync(password, 10),
        email
      });
 
      await user.save();
      res.status(201).json({ message: '注册成功' });
    } catch (err) {
      res.status(500).json({ message: '服务器错误' });
    }
  }
);
 
// 登录接口
router.post('/login', 
  [
    body('username').not().isEmpty().withMessage('用户名不能为空'),
    body('password').not().isEmpty().withMessage('密码不能为空')
  ], 
  async (req, res) => {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({ errors: errors.array() });
    }
 
    const { username, password } = req.body;
 
    try {
      const user = await User.findOne({ username });
      if (!user) {
        return res.status(401).json({ message: '用户不存在' });
      }
 
      if (!bcrypt.compareSync(password, user.password)) {
        return res.status(401).json({ message: '密码错误' });
      }
 
      const token = jwt.sign({ userId: user.id }, process.env.JWT_SECRET, { expiresIn: '1h' });
      res.status(200).json({ token, userId: user.id, username: user.username });
    } catch (err) {
      res.status(500).json({ message: '服务器错误' });
    }
  }
);
 
module.exports = router;
这段代码实现了用户注册和登录的接口,使用了Express框架和express-validator中间件来处理请求验证,并使用bcryptjs进行密码散列,以及jsonwebtoken生成用户认证token。代码示例中包含了错误处理和用户存在性的检查,有助于理解如何在实际应用中处理用