简介:本文深入探讨Node.js环境下登录接口与注册接口的实现方案,涵盖加密技术、JWT认证、接口安全设计及错误处理机制,提供可复用的代码示例与最佳实践。
在Web开发中,用户认证系统是任何应用程序的核心组件。Node.js凭借其非阻塞I/O和轻量级特性,成为构建高性能认证接口的理想选择。本章将系统讲解如何使用Node.js结合Express框架、数据库(如MongoDB)及加密技术,实现安全可靠的登录与注册接口。
// package.json依赖配置示例{"dependencies": {"express": "^4.18.2","mongoose": "^7.0.0","bcryptjs": "^2.4.3","jsonwebtoken": "^9.0.0","express-validator": "^7.0.1"}}
const mongoose = require('mongoose');const userSchema = new mongoose.Schema({username: { type: String, required: true, unique: true },email: { type: String, required: true, unique: true },password: { type: String, required: true },createdAt: { type: Date, default: Date.now }});module.exports = mongoose.model('User', userSchema);
const express = require('express');const router = express.Router();const User = require('../models/User');const bcrypt = require('bcryptjs');const { body, validationResult } = require('express-validator');// 注册路由处理router.post('/register', [body('username').isLength({ min: 3 }).withMessage('用户名至少3个字符'),body('email').isEmail().withMessage('请输入有效邮箱'),body('password').isLength({ min: 6 }).withMessage('密码至少6个字符')], async (req, res) => {const errors = validationResult(req);if (!errors.isEmpty()) {return res.status(400).json({ errors: errors.array() });}try {const { username, email, password } = req.body;// 检查用户是否存在let user = await User.findOne({ email });if (user) {return res.status(400).json({ msg: '用户已存在' });}// 密码哈希处理const salt = await bcrypt.genSalt(10);const hashedPassword = await bcrypt.hash(password, salt);// 创建新用户user = new User({username,email,password: hashedPassword});await user.save();res.status(201).json({ msg: '用户注册成功' });} catch (err) {console.error(err.message);res.status(500).send('服务器错误');}});
const jwt = require('jsonwebtoken');const secret = process.env.JWT_SECRET || 'your-secret-key';router.post('/login', [body('email').isEmail().withMessage('请输入有效邮箱'),body('password').exists().withMessage('请输入密码')], async (req, res) => {const errors = validationResult(req);if (!errors.isEmpty()) {return res.status(400).json({ errors: errors.array() });}try {const { email, password } = req.body;// 查找用户const user = await User.findOne({ email });if (!user) {return res.status(400).json({ msg: '无效的凭证' });}// 验证密码const isMatch = await bcrypt.compare(password, user.password);if (!isMatch) {return res.status(400).json({ msg: '无效的凭证' });}// 生成JWTconst payload = {user: {id: user.id}};jwt.sign(payload, secret, { expiresIn: '1h' }, (err, token) => {if (err) throw err;res.json({ token });});} catch (err) {console.error(err.message);res.status(500).send('服务器错误');}});
const auth = (req, res, next) => {const token = req.header('x-auth-token');if (!token) {return res.status(401).json({ msg: '未授权,缺少token' });}try {const decoded = jwt.verify(token, secret);req.user = decoded.user;next();} catch (err) {res.status(401).json({ msg: 'Token无效' });}};
project/├── config/│ └── db.js # 数据库连接├── models/│ └── User.js # 用户模型├── routes/│ ├── auth.js # 认证路由│ └── users.js # 用户相关路由├── middleware/│ └── auth.js # 认证中间件├── .env # 环境变量└── server.js # 主应用文件
通过本章的学习,读者应已掌握:
这些技能是构建现代Web应用程序的基础,建议读者在实际项目中不断实践和完善。后续章节将探讨如何基于这些认证接口构建完整的用户管理系统。