简单的登录注册连接数据库

脚手架快速生成项目:

目录解构:

简单的登录注册连接数据库_第1张图片

 中间件:

简单的登录注册连接数据库_第2张图片

主要代码如下:

1.index.js

var express = require('express');
let svg = require('svg-captcha');
let mysql = require('../tools/db');
var router = express.Router();

/* 在cookie和session时效内不需要再次输入密码和账号即可进入该网站 */
router.get('/', function (req, res, next) {
  //实现权限管理访问
  if (!req.signedCookies.username) {
    res.render('login.ejs');
  } else {
    if (!req.session.sex) {
      res.render('login.ejs');
    } else {
      res.send(`登陆成功`);
    }
  }
});

//渲染登录页
router.get('/login', (req, res) => {
  res.render('login.ejs');
})

//渲染注册页
router.get('/register', (req, res) => {
  res.render('register.ejs');
})

//注册功能
router.post('/register', async (req, res) => {
  let {
    username,
    password,
    code
  } = req.body;

  console.log(req.session.stat, code);
  if ((req.session.stat).toUpperCase() != code.toUpperCase()) {
    res.send('验证失败,请重新输入');
    return;
  }

  let selectData = await mysql.query('select * from student where username=? and password=?', [username, password]);
  //先查询数据库看该用户名是否存在  存在提示用户名已存在  不存在添加
  if (selectData.length > 0) {
    res.send('用户名已存在');
  } else {
    //添加
    let data = await mysql.query('insert into student(username,password) values(?,?)', [username, password]);
    if (data.affectedRows > 0) {
      res.send('添加成功');
    } else {
      res.send('添加失败');
    }
  }

})
//验证码
router.get('/yzm', (req, res) => {
  let options = {
    size: 4, // 验证码长度
    width: 200, //验证码图片宽度
    height: 80, //验证码图片的高度
    background: "#fff", //验证码图片的背景颜色
    noise: 4, //验证码图片中的干扰线
    fontSize: 80, //验证码图片中文字大小
    color: true, //验证码图片中文字颜色
    ignoreChars: "Il1o0" //容易混淆的字符不要出现在验证码中
  }
  let svg1 = svg.create(options);
  req.session.stat = svg1.text;
  res.type('svg');
  res.send(svg1.data);
})

//登录功能
router.post('/login', async (req, res) => {
  let {
    username,
    password,
  } = req.body;

  let selectData = await mysql.query('select * from student where username=? and password=?', [username, password]);
  for (let i of selectData) {
    if (i.username == username && i.password == password) {
      //2分钟cookie失效
      res.cookie("username", 'lisi', {
        maxAge: 1000 * 60 * 2,
        signed: true
      });

      req.session.sex = '男';
      res.send('登陆成功');
    } else {
      res.send('登陆失败');
    }
  }
})

module.exports = router;

 2.app.js

var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var session = require('express-session');
var logger = require('morgan');

var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({
  extended: false
}));
let secret = 'ggwyehsdnf';
app.use(cookieParser(secret));
let options = {
  secret,
  resave: false,
  saveUninitialized: true
}
app.use(session(options));
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', indexRouter);
app.use('/users', usersRouter);

// catch 404 and forward to error handler
app.use(function (req, res, next) {
  next(createError(404));
});

// error handler
app.use(function (err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;

3.连接数据库工具

let mysql = require('mysql');
let options = require('./config');
//1.创建链接
let conn = mysql.createConnection(options);
//2.连接数据库
conn.connect((err) => {
    if (err) {
        console.log('连接数据库失败');
        return;
    }
})
//3.CURD
function query(sql, arr) {
    return new Promise((resolve, reject) => {
        conn.query(sql, arr, (err, results) => {
            if (!err) {
                resolve(results);
            } else {
                reject(err);
            }
        })
    })
}

//4.关闭连接
function close() {
    conn.end();
}

module.exports = {
    query,
    close,
}

4.工具配置:

let options = {
    host: '127.0.0.1',
    port: 3306,
    user: 'root',
    password: 'root',
    database: 'student',
}

module.exports = options;

你可能感兴趣的:(前端)