Node.js用户注册与登录实现
开发
实现用户注册与登录功能的完整解决方案
在现代Web应用中,用户注册与登录是基本且核心的功能之一。本文将以Node.js和Express框架为例,结合MongoDB数据库,详细介绍如何实现一个简单且安全的用户注册与登录功能。
功能描述
- 用户可以通过用户名和密码注册账号。
- 注册时对密码进行加密存储。
- 用户可以使用注册的账号登录。
- 登录时验证用户名和密码,成功后返回登录成功消息。
- 登录失败时返回错误提示。
技术栈
- Node.js
- Express
- MongoDB(通过Mongoose操作)
- bcrypt(用于密码加密)
- body-parser(解析请求体)
方案设计
- 设计用户模型(User),包含用户名(唯一)和加密后的密码。
- 注册接口:接收用户名和密码,检查用户名是否已被占用,若未占用,使用bcrypt对密码加密后存储。
- 登录接口:接收用户名和密码,查询用户,使用bcrypt比对密码,验证成功则返回成功响应。
- 错误处理和简单输入校验。
代码实现
1. 初始化项目及安装依赖
npm init -y
npm install express mongoose bcrypt body-parser
2. app.js
const express = require('express');
const mongoose = require('mongoose');
const bcrypt = require('bcrypt');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.json());
// 连接到MongoDB
mongoose.connect('mongodb://localhost:27017/userAuthDemo', {
useNewUrlParser: true,
useUnifiedTopology: true,
});
// 定义用户模型
const userSchema = new mongoose.Schema({
username: { type: String, unique: true, required: true },
password: { type: String, required: true }, // 存储加密后的密码
});
const User = mongoose.model('User', userSchema);
// 注册接口
app.post('/register', async (req, res) => {
const { username, password } = req.body;
// 简单校验
if (!username || !password) {
return res.status(400).json({ message: '用户名和密码不能为空' });
}
try {
// 检查用户是否存在
const existingUser = await User.findOne({ username });
if (existingUser) {
return res.status(409).json({ message: '用户名已存在' });
}
// 加密密码
const saltRounds = 10;
const hashedPassword = await bcrypt.hash(password, saltRounds);
// 创建用户
const newUser = new User({ username, password: hashedPassword });
await newUser.save();
res.status(201).json({ message: '注册成功' });
} catch (err) {
res.status(500).json({ message: '服务器错误' });
}
});
// 登录接口
app.post('/login', async (req, res) => {
const { username, password } = req.body;
if (!username || !password) {
return res.status(400).json({ message: '用户名和密码不能为空' });
}
try {
const user = await User.findOne({ username });
if (!user) {
return res.status(401).json({ message: '用户名或密码错误' });
}
// 比较密码
const isMatch = await bcrypt.compare(password, user.password);
if (!isMatch) {
return res.status(401).json({ message: '用户名或密码错误' });
}
res.json({ message: '登录成功' });
} catch (err) {
res.status(500).json({ message: '服务器错误' });
}
});
app.listen(3000, () => {
console.log('服务器运行在 http://localhost:3000');
});
使用步骤
- 确保本地已安装并启动MongoDB服务。
- 在项目根目录下运行
node app.js
启动服务器。 - 使用Postman或curl工具向
/register
发送POST请求:{ "username": "testuser", "password": "123456" }
- 若注册成功,返回
注册成功
。 - 使用同样方式向
/login
发送POST请求,输入注册账号和密码。 - 成功时返回
登录成功
,否则返回错误信息。
总结
本文从需求分析、方案设计到代码实现,完整演示了如何构建一个基本的用户注册与登录功能。通过bcrypt加密保障用户密码安全;借助MongoDB持久化数据,Node.js搭建高性能后台。此方案可作为初学者学习和中小型项目的实用参考。
编辑:一起学习网