注册

node.js实现简单登录注册功能

下面是简单登录注册功能的 node.js 实现完整攻略。

1. 确定需求和技术栈

我们首先需要明确需求:实现用户的注册和登录功能。

而我们使用的后端技术栈包括:

  • Node.js
  • Express.js
  • MongoDB
  • HTML/CSS/JS (前端页面)

2. 设计数据库

我们需要设计一个用户的数据模型,在 MongoDB 中存储,可以使用 Mongoose 来操作 MongoDB。

const mongoose = require('mongoose');

const UserSchema = new mongoose.Schema({
  username: {
    type: String,
    required: true,
    unique: true,
    trim: true,
  },
  password: {
    type: String,
    required: true,
  },
});

const User = mongoose.model('User', UserSchema);

module.exports = User;

上面是用户的数据模型,包括用户名和密码两个字段。

3. 实现注册和登录

下面是注册和登录的示例代码:

const express = require('express');
const bodyParser = require('body-parser');
const bcrypt = require('bcrypt');
const User = require('./models/user');

const app = express();
const saltRounds = 10;

// 通过中间件解析请求体
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

// 注册
app.post('/register', async (req, res) => {
  const { username, password } = req.body;
  const hashedPassword = await bcrypt.hash(password, saltRounds); // 对密码进行加密
  const user = new User({ username, password: hashedPassword });
  try {
    await user.save();
    res.send('注册成功');
  } catch (err) {
    console.error(err);
    res.status(500).send('注册失败');
  }
});

// 登录
app.post('/login', async (req, res) => {
  const { username, password } = req.body;
  const user = await User.findOne({ username });
  if (!user) {
    res.status(401).send('用户名不存在');
  } else {
    const validPassword = await bcrypt.compare(password, user.password); // 和数据库中的密码作比较
    if (validPassword) {
      res.send('登录成功');
    } else {
      res.status(401).send('密码错误');
    }
  }
});

// 监听端口
app.listen(5000, () => {
  console.log('Server started on port 5000');
});

上述代码中,我们使用 bcrypt 库对用户的密码进行了加密,对于注册和登录请求,可以分别通过 /register/login 的接口来实现。在 /login 接口中,我们也使用 bcrypt 库对明文密码进行加密,并将加密后的密码与数据库中的加密密码进行比较,从而实现登录。

4. 设计前端页面

最后,我们来设计前端页面,包括注册页面和登录页面。这里提供一个简单的示例页面:





  
  登录/注册页



  

注册




登录



我们通过 HTML 设计了一个包含注册和登录的页面,在表单中分别输入用户名和密码,然后通过 POST 请求将数据发送给后端接口。

至此,我们就成功实现了一个简单的登录注册功能。