今天没废话,直接看代码。
npm i express
npm i mysql
npm i cors
npm i body-parser
npm i cookie-parser
npm i jsonwebtoken
npm i nodemailer
const express = require('express')
const router = express.Router()
// token生成插件模块
const jwt = require('jsonwebtoken');
// Token签名
var secret = 'I LOVE LXD';
// 引入数据库
const mysql = require('../mysql/mysql')
var connection = null;
router.post('/login', (req, res) => {
// 数据库连接
connection = mysql.createConnection();
connection.connect();
// 查询语句
var sql = 'SELECT * FROM user_table Where uemail=?';
// 前端传来参数
var params = [req.body.email, req.body.pwd]
//登录验证
connection.query(sql,req.body.email, function (err, result) {
// 存储返回结果
var result1
if (err) {
console.log('[SELECT ERROR] - ', err.message);
result1 = {
code: 501,
msg: '数据库链接失败...'
}
return;
} else {
// 用户没有输入时
if (req.body.email === undefined || req.body.pwd === undefined) {
result1 = {
code: 401,
msg: '邮箱或密码不能为空',
xl: 0
}
} else {
if(result.length!==0){
console.log(result)
for (let i = 0; i < result.length; i++) {
// 邮箱或者密码不正确的时候
if (req.body.email !== result[i].uemail || req.body.pwd !== result[i].upwd) {
result1 = {
code: 400,
result: '邮箱或者密码错误!',
xl: 1
}
}
// 邮箱和密码输入正确
if (req.body.email === result[i].uemail && req.body.pwd === result[i].upwd) {
// 获取客户端的ip地址
var clientIp = getIp(req)
// 传输的token内容
let payload = { uid: result[i].uid ,ip:clientIp};
let token = jwt.sign(payload, secret);
console.log("用户信息存储token:"+token)
// 写入cookie中
res.cookie('tooken', token, { httpOnly: true, signed: true })
// 返回结果
result1 = {
code: 200,
token: token,
msg: '信息正确,返回登录',
xl:2,
ip:clientIp
}
}
}
}else{
result1={
code:402,
msg:'账号不存在请注册!'
}
}
}
}
// 返回结果,关闭数据库连接
res.send(result1)
connection.end();
});
})
//通过req的hearers来获取客户端ip
var getIp = function (req) {
var ip = req.headers['x-real-ip'] || req.headers['x-forwarded-for'] || req.connection.remoteAddres || req.socket.remoteAddress || '';
if (ip.split(',').length > 0) {
ip = ip.split(',')[0];
}
return ip;
};
// 返回router,映射出去
module.exports = router
const express = require('express')
const router = express.Router()
// 引入数据库
const mysql = require('../mysql/mysql')
var connection = null;
const nodemailer = require('nodemailer');
// 存储验证码以供注册使用
var code = ''
// 存储用户注册时的邮箱以防伪注册
var oldemail = ''
// 获取验证码
router.get('/sendemail/register', (req, res) => {
if (req.query.email === undefined) {
res.send({
code: 400,
msg: '必填参数不能为空,请检查!'
})
} else {
//2. 创建运输对象
let transporter = nodemailer.createTransport({
host: 'smtp.qq.com',
secure: true,
port: 465,
auth: {
user: '', //qq邮箱账号
pass: '' //邮箱的授权码
}
})
// 存储验证码
code = YzId(5)
// 存储邮箱
oldemail = req.query.email
//3.配置发送邮件的信息
let mailOptions = {
from: '', // 发送者
to: req.query.email, // 传过来的邮箱
subject: '注册验证码', // 邮件标题
html: `验证码为:${code},序号:1,注册使用`
};
//4.发送邮件
transporter.sendMail(mailOptions, function (err, data) {
//回调函数,用于判断邮件是否发送成功
if (err) {
console.log('发送异常' + err)
} else {
let result = {
code: 200,
msg: '验证码发送成功,请及时查收!',
}
res.send(result)
}
})
}
})
router.post('/register', (req, res) => {
// 数据库连接
connection = mysql.createConnection();
connection.connect();
// 查询语句
var sql = 'SELECT * FROM user_table Where uemail=?';
var params = req.body.email
try {
if (req.body.code !== code || req.body.code === undefined) {
res.send({
code: 403,
msg: '验证码有误'
})
} else {
// 用户没有输入时
if (req.body.email === undefined || req.body.name === undefined || req.body.pwd === undefined) {
res.send({
code: 401,
msg: '必须参数为空,已知异常,请重新输入!',
xl: 0
})
} else {
if (req.body.email !== oldemail) {
res.send({
code: 405,
msg: '邮箱不一致,请检查!'
})
} else {
connection.query(sql, params, (err, result) => {
if (err) {
console.log('注册查重异常,请稍后重试!')
return
} else {
var result1;
// 查询结果数组长度不为零,就是有存在的数据
if (result.length !== 0) {
res.send({
code: 202,
msg: '该邮箱已经存在,请重新输入!',
xl: 1
})
} else {
// 没有数据时候,进行注册
// 获取客户端的ip地址
var clientIp = getIp(req)
// 插入数据的sql语句
let sql = "INSERT INTO user_table(uid,uname,upwd,uemail,uimg,utime,uintroduction,uip,ustatus) VALUES(?,?,?,?,?,?,?,?,?)"
// 参数
let params = [YzId(6), req.body.name, req.body.pwd, req.body.email, 'http://192.168.1.80:3333/static/default.jpg', timestampToTime(Date.now()), "用户太懒了,还没有简介...", clientIp, '1']
connection.query(sql, params, (err, result) => {
if (err) {
result1 = {
code: 401,
msg: '注册数据库异常,请稍后重试!'
}
} else {
result1 = {
code: 200,
result: {
msg: "注册成功,请返回登录!",
IP: clientIp,
id: YzId(6)
}
}
// 完成后进行验证码清空以及邮箱清空
code=''
oldemail=''
}
// 返回结果
res.send(result1)
})
}
}
// 关闭数据库连接
connection.end();
})
}
}
}
} catch (e) {
// 异常情况
res.send(e)
connection.end();
}
})
// 随机生成6位id
function YzId(n) {
let str = "";
const arr = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "1", "2", "3", "4", "5", "6", "7", "8", "9", "0",
];
for (let i = 0; i < n; i++) {
str += arr[Math.floor(Math.random() * arr.length)];
}
return str;
}
//通过req的hearers来获取客户端ip
var getIp = function (req) {
var ip = req.headers['x-real-ip'] || req.headers['x-forwarded-for'] || req.connection.remoteAddres || req.socket.remoteAddress || '';
if (ip.split(',').length > 0) {
ip = ip.split(',')[0];
}
return ip;
};
// 时间转换以及补零操作
function timestampToTime(timestamp) {
var date = new Date(timestamp)
var Y = date.getFullYear() + '-'
var M = (date.getMonth() + 1).toString().padStart(2, '0') + '-'
var D = date.getDate().toString().padStart(2, '0') + ' '
var h = date.getHours().toString().padStart(2, '0') + ':'
var m = date.getMinutes().toString().padStart(2, '0') + ':'
var s = date.getSeconds().toString().padStart(2, '0')
return Y + M + D + h + m + s
}
// 映射出
module.exports = router
const express = require('express')
const router = express.Router()
const nodemailer = require('nodemailer');
// 引入数据库
const mysql = require('../mysql/mysql')
var connection = null;
router.post('/forget/user', (req, res) => {
if (req.body.email === undefined) {
res.send({
code: 400,
msg: '必填参数不能为空,请仔细检查'
})
} else {
// 数据库连接
connection = mysql.createConnection();
connection.connect();
var result1
var sql = "SELECT * From user_table Where uemail=?"
var params = req.body.email
connection.query(sql, params, (err, result) => {
if (err) {
console.log('查询忘记密码邮箱数据库异常')
return
} else {
if (result.length !== 0) {
forget(req.body.email, result[0].uname, result[0].upwd,req)
result1 = {
code: 200,
msg: '您的个人信息已经发送至您的邮箱,请注意查收!'
}
} else {
result1 = {
code: 401,
msg: '暂无此用户,请先去注册!'
}
}
}
// 返回结果,关闭数据库连接
res.send(result1)
connection.end();
})
}
})
// 发送邮件找回密码
function forget(email, name, pwd,req) {
//2. 创建运输对象
let transporter = nodemailer.createTransport({
host: 'smtp.qq.com',
secure: true,
port: 465,
auth: {
user: '', //qq邮箱账号
pass: '' //邮箱的授权码
}
})
//3.配置发送邮件的信息
let mailOptions = {
from: '', // 发送者
to: email, // 传过来的邮箱
subject: '忘记密码找回', // 邮件标题
html: `用户名:${name},
邮箱:${email},
密码:${pwd},
操作ip:${getIp(req)}(我们不会存储您的IP信息,仅作为提示所用。),
请妥善保管您的个人信息!`
};
//4.发送邮件
transporter.sendMail(mailOptions, function (err, data) {
//回调函数,用于判断邮件是否发送成功
if (err) {
console.log('发送异常' + err)
} else {
let data = {
code: 200,
msg: '验证码发送成功',
}
res.send(data)
}
})
}
//通过req的hearers来获取客户端ip
var getIp = function (req) {
var ip = req.headers['x-real-ip'] || req.headers['x-forwarded-for'] || req.connection.remoteAddres || req.socket.remoteAddress || '';
if (ip.split(',').length > 0) {
ip = ip.split(',')[0];
}
return ip;
};
module.exports = router
const mysql = require('mysql')
function createConnection() {
const connection = mysql.createConnection({
host: '', //地址
user: '', //用户名
password: '', //密码
port: '', //端口
database: '' //数据库名
});
return connection;
}
module.exports.createConnection = createConnection;
// 引入express框架
const express = require('express')
// 解析参数格式
const bodyParser = require('body-parser')
// 跨域
const cors = require('cors')
// 文件路径
const path = require('path')
// 操作cookie模块
const cookieParser = require('cookie-parser');
// 实例化
const app = express()
// 解决跨域问题
app.use(cors());
// 解析 application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({
extended: false
}));
// 解析 application/json
app.use(bodyParser.json());
// 加入cookie签名
app.use(cookieParser('I LOVE LXD')); //使用cookie中间件,加密值为:I LOVE LXD
//设置跨域访问
app.all('*', function (req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "content-type");
res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
res.header("X-Powered-By", ' 3.2.1')
res.header("Content-Type", "application/json;charset=utf-8");
next();
})
// 静态文件
app.use('/static', express.static(path.join(__dirname, 'public')));
// 引入登录模块
const login = require('./router/login')
app.use(login)
// 引入注册模块
const register=require('./router/register')
app.use(register)
// 引入验证码发送模块
const email=require('./email/email')
app.use(email)
// 引入忘记密码模块
const forget=require('./router/forget')
app.use(forget)
// 监听服务开启
app.listen('3333', '0.0.0.0', (res) => {
console.log('Server running http://0.0.0.0:3333')
})
有问题及时留言沟通哦