使用Node.JS实现注册和登录功能(笔记)
server.js 页面代码
// 引入需要的依赖 const express=require('express'); //框架名 const cookieParser=require('cookie-parser'); // const cookieSession=require('cookie-session'); const bodyParser=require('body-parser'); //获取post请求数据 //获取post数据配置 var server=express(); server.use(bodyParser.urlencoded({extended:false})) server.use(bodyParser.json()) //设置跨域访问 server.all("*",function(req,res,next){ //设置允许跨域的域名,*代表允许任意域名跨域 res.header("Access-Control-Allow-Origin","*"); //允许的header类型 res.header("Access-Control-Allow-Headers","content-type"); //跨域允许的请求方式 res.header("Access-Control-Allow-Methods","DELETE,PUT,POST,GET,OPTIONS"); if (req.method.toLowerCase() == 'options'){ // res.send(200); //让options尝试请求快速结束 res.sendStatus(200) }else{ next(); } }) server.listen(9111); // cookie session (function(){ server.use(cookieParser()); server.use(cookieSession({ name:"sess_id", keys:["232342342342","12312313213","sdfsaf23r34r3f","123124134dasda"], maxAge:20*60*1000 })) })(); // route 小型的express 路由 server.use('/aaa/',require('./route/ceshi')()); //测试 server.use('/admin/',require('./route/admin')());
注册登录接口代码
// 引入依赖 const express = require('express'); const mysql = require('mysql'); const crypto = require('crypto'); //加载crypto库 const setPassword = require('../libs/setPassword') //字符串转换MD5函数 //连接数据库 var connection = mysql.createConnection({ host: 'localhost', user: 'root', password: '123456', database: 'boke' }); connection.connect(); module.exports = function () { var route = express.Router(); route.post('/reg', function (req, res) { let username = req.body.username; //用户名 let password = setPassword(req.body.password, crypto); //密码 connection.query(`SELECT * FROM admin WHERE username='${username}'`, function (err, data) { if (err) { res.send(err).end(); } else { if (data.length == 0) { let sqltext = `INSERT INTO admin (username,password) VALUES('${username}','${password}')`; connection.query(sqltext, function (err, data) { if (err) { res.send(err).end() } else { res.send({ code: 200, msg: "注册成功!" }).end(); } }) } else { res.send({ code: 500, msg: "用户名已存在,请重新注册!" }).end(); } } }) }) route.post('/login', function (req, res) { let username = req.body.username; //用户名 let password = setPassword(req.body.password, crypto); //密码 connection.query(`SELECT * FROM admin WHERE username='${username}'`, function (err, data) { if (err) { res.send(err).end(); } else { if (data.length > 0) { if (data[0].password === password) { res.send({ code: 200, data: data[0] }).end(); } else { res.send({ code: 500, msg: "用户名或密码错误" }).end(); } } else { res.send({ code: 500, msg: "用户名或密码错误" }).end(); } } }) }) return route }
setPassword 函数
function setPassword(pwd,crypto){ let password=`${pwd}guoyakun` const md5 = crypto.createHash('md5'); md5.update(password); var newpwd=md5.digest('hex'); return newpwd } module.exports=setPassword