首页 > 编程语言 >一个练习项目,好玩的bbs-nodejs-restify

一个练习项目,好玩的bbs-nodejs-restify

时间:2024-09-02 14:39:15浏览次数:11  
标签:nodejs res sessionId params userinfo restify var bbs id

代码:

var restify=require('restify')
var server=restify.createServer()
const md5 = require('md5');
const querystring = require('querystring');

//npm install restify

var secretKey = 'saacac3423@21212';
var pagesize = 20;

var mysql      = require('mysql');
var connection = mysql.createConnection({
  host     : '127.0.0.1',
  user     : 'root',
  password : '123456',
  database : 'my_bbs'
});
 
connection.connect();

function retsuccess(data){
    var result = JSON.stringify({'code' : 0, 'msg' : '', 'data' : data});
    return result;
}

function reterror(code, msg){
    var result = JSON.stringify({'code' : code, 'msg' : msg, 'data' : ''});
    return result;
}

function formatDateTime(dateString) {
  const date = new Date(dateString);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');
  
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}

//异步函数,用于执行SQL查询
async function queryDatabase(sql, values) {
    return new Promise((resolve, reject) => {
        connection.query(sql, values, (error, results, fields) => {
            if (error) reject(error);
            resolve(results);
        });
    });
}

server.get('/', async (req, res)=>{
    res.header('Server', 'nodejs-restify')
    res.header('Content-Type', 'text/html');
    
    res.send("此站接口使用nodejs-restify实现,<a href='api.html' target='_blank'>接口列表</a>");
});

server.get('/user/register', async (req, res) => {
    res.header('Server', 'nodejs-restify')
    res.header('Content-Type', 'text/html');
    var params = querystring.parse(req.getQuery());
    
    var username = params.username;
    var nickname = params.nickname;
    var password = params.password;
    var passwordMd5 = md5(password);
    
    var sql1 = "select id,username,nickname,addTime from user where username='"+username+"'";
    var results = await queryDatabase(sql1);
    var userinfo = results[0];
    
    if(!userinfo){
        var sql2 = "insert into user(username, password, nickname) value(?, ?, ?)";
        var addSqlParams = [username, passwordMd5, nickname];
        var result = await queryDatabase(sql2, addSqlParams);
        res.send(retsuccess(result.insertId));
    }
    else{
        res.send(reterror(1, '用户名已经存在'));
    }
});

server.get('/user/login', async (req, res) => {
    res.header('Server', 'nodejs-restify')
    res.header('Content-Type', 'text/html');
    var params = querystring.parse(req.getQuery());
    
    var username = params.username;
    var password = params.password;
    var passwordMd5 = md5(password);
    
    var sql1 = "select id,username,nickname,addTime from user where username='"+username+"' and password='"+passwordMd5+"'";
    var results = await queryDatabase(sql1);
    var userinfo = results[0];
    
    if(userinfo){
        var sessionId = md5(secretKey + userinfo['id'] + userinfo['addTime']);
        var sql2 = "update user set sessionId='"+sessionId+"' where id="+userinfo['id'];
        var results = await queryDatabase(sql2);
        userinfo['sessionId'] = sessionId;
        res.send(retsuccess(userinfo));
    }
    else{
        res.send(reterror(1, '用户名或者密码错误'));
    }
});

server.get('/user/logout', async (req, res) => {
    res.header('Server', 'nodejs-restify')
    res.header('Content-Type', 'text/html');
    var params = querystring.parse(req.getQuery());
    
    var sessionId = params.sessionId;
    
    var sql1 = "select id,username,nickname,addTime from user where sessionId='"+sessionId+"'";
    var results = await queryDatabase(sql1);
    var userinfo = results[0];
    
    var sql2 = "update user set sessionId='' where id="+userinfo['id'];
    var results = await queryDatabase(sql2);
    userinfo['sessionId'] = '';
    
    res.send(retsuccess(userinfo));
});

server.get('/user/getuserinfo', async (req, res) => {
    res.header('Server', 'nodejs-restify')
    res.header('Content-Type', 'text/html');
    var params = querystring.parse(req.getQuery());
    
    var sessionId = params.sessionId;

    var sql1 = "select id,username,nickname,addTime,sessionId from user where sessionId='"+sessionId+"'";
    var results = await queryDatabase(sql1);
    var userinfo = results[0];
    
    res.send(retsuccess(userinfo));
});

server.get('/post/list', async (req, res) => {
    res.header('Server', 'nodejs-restify')
    res.header('Content-Type', 'text/html');
    var params = querystring.parse(req.getQuery());
    
    var page = params.page;
    var keyword = params.keyword;
    if(page <= 0){
        page = 1;
    }
    
    var start = (page - 1) * pagesize;
    var addsql = " isDel=0 ";
    if(keyword){
        addsql = " isDel=0 and title like '%"+keyword+"%' ";
    }
    
    var sql1 = "select count(1) as count from content where "+addsql;
    var results = await queryDatabase(sql1);
    var count = results[0]['count'];
    var totalpage = Math.ceil(count / pagesize);
    
    var sql2 = "select id,title,userId,userNickename,replyNum,updateTime from content where "+addsql+" order by updateTime desc limit "+start+","+pagesize;
    var results = await queryDatabase(sql2);
    for(var i=0; i<results.length; i++){
        results[i]['updateTime'] = formatDateTime(results[i]['updateTime']);
    }
    
    res.send(retsuccess({'totalpage' : totalpage, 'data' : results}));
});

server.get('/post/detail', async (req, res) => {
    res.header('Server', 'nodejs-restify')
    res.header('Content-Type', 'text/html');
    var params = querystring.parse(req.getQuery());
    
    var id = params.id;
    
    var sql1 = "select id,title,content,userId,userNickename,replyNum,updateTime from content where isDel=0 and id="+id;
    var results = await queryDatabase(sql1);
    
    res.send(retsuccess(results[0]));
});

server.get('/post/add', async (req, res) => {
    res.header('Server', 'nodejs-restify')
    res.header('Content-Type', 'text/html');
    var params = querystring.parse(req.getQuery());
    
    var title = params.title;
    var content = params.content;
    var sessionId = params.sessionId;
    
    var sql1 = "select id,username,nickname,addTime,sessionId from user where sessionId='"+sessionId+"'";
    var results = await queryDatabase(sql1);
    var userinfo = results[0];
    
    var sql2 = "insert into content(title, content, userId, userNickename) value(?, ?, ?, ?)";
    var addSqlParams = [title, content, userinfo['id'], userinfo['nickname']];
    var result = queryDatabase(sql2, addSqlParams);
    
    res.send(retsuccess(result.insertId));
});

server.get('/post/edit', async (req, res) => {
    res.header('Server', 'nodejs-restify')
    res.header('Content-Type', 'text/html');
    var params = querystring.parse(req.getQuery());
    
    var id = params.id;
    var title = params.title;
    var content = params.content;
    var sessionId = params.sessionId;
    
    var sql1 = "select id,username,nickname,addTime,sessionId from user where sessionId='"+sessionId+"'";
    var results = await queryDatabase(sql1);
    var userinfo = results[0];
    
    var sql2 = "update content set title=?,content=?,userId=?,userNickename=? where id=? and userId=?";
    var addSqlParams = [title, content, userinfo['id'], userinfo['nickname'], id, userinfo['id']];
    var result = queryDatabase(sql2, addSqlParams);
    
    res.send(retsuccess(''));
});

server.get('/post/delete', async (req, res) => {
    res.header('Server', 'nodejs-restify')
    res.header('Content-Type', 'text/html');
    var params = querystring.parse(req.getQuery());
    
    var id = params.id;
    var sessionId = params.sessionId;
    
    var sql1 = "select id,username,nickname,addTime,sessionId from user where sessionId='"+sessionId+"'";
    var results = await queryDatabase(sql1);
    var userinfo = results[0];
    
    var sql2 = "update content set isDel=1 where id=? and userId=?";
    var addSqlParams = [id, userinfo['id']];
    var result = queryDatabase(sql2, addSqlParams);
    
    res.send(retsuccess(''));
});

server.get('/reply/list', async (req, res) => {
    res.header('Server', 'nodejs-restify')
    res.header('Content-Type', 'text/html');
    var params = querystring.parse(req.getQuery());
    
    var page = params.page;
    var contentId = params.contentId;
    if(page <= 0){
        page = 1;
    }
    
    var start = (page - 1) * pagesize;
    var addsql = " isDel=0 and contentId="+contentId+" ";
    
    var sql1 = "select count(1) as count from reply where "+addsql;
    var results = await queryDatabase(sql1);
    var count = results[0]['count'];
    var totalpage = Math.ceil(count / pagesize);
    
    var sql2 = "select id,content,replyUserId,replyUserNickename,addTime from reply where "+addsql+" order by id asc limit "+start+","+pagesize;
    var results = await queryDatabase(sql2);
    for(var i=0; i<results.length; i++){
        results[i]['addTime'] = formatDateTime(results[i]['addTime']);
    }
    
    res.send(retsuccess({'totalpage' : totalpage, 'data' : results}));
});

server.get('/reply/detail', async (req, res) => {
    res.header('Server', 'nodejs-restify')
    res.header('Content-Type', 'text/html');
    var params = querystring.parse(req.getQuery());
    
    var id = params.id;
    
    var sql1 = "id,content,replyUserId,replyUserNickename,addTime from reply where id="+id;
    var results = await queryDatabase(sql1);
    
    res.send(retsuccess(results[0]));
});

server.get('/reply/add', async (req, res) => {
    res.header('Server', 'nodejs-restify')
    res.header('Content-Type', 'text/html');
    var params = querystring.parse(req.getQuery());
    
    var contentId = params.contentId;
    var content = params.content;
    var sessionId = params.sessionId;
    
    var sql1 = "select id,username,nickname,addTime,sessionId from user where sessionId='"+sessionId+"'";
    var results = await queryDatabase(sql1);
    var userinfo = results[0];
    
    var sql2 = "update content set replyNum=replyNum+1 where id=?";
    var addSqlParams2 = [contentId];
    var result = await queryDatabase(sql2, addSqlParams2);
    
    var sql3 = "insert into reply(contentId, content, replyUserId, replyUserNickename) value(?, ?, ?, ?)";
    var addSqlParams3 = [contentId, content, userinfo['id'], userinfo['nickname']];
    var result = await queryDatabase(sql3, addSqlParams3);
    
    res.send(retsuccess(result.insertId));
});

server.get('/reply/edit', async (req, res) => {
    res.header('Server', 'nodejs-restify')
    res.header('Content-Type', 'text/html');
    var params = querystring.parse(req.getQuery());
    
    var id = params.id;
    var content = params.content;
    var sessionId = params.sessionId;
    
    var sql1 = "select id,username,nickname,addTime,sessionId from user where sessionId='"+sessionId+"'";
    var results = await queryDatabase(sql1);
    var userinfo = results[0];
    
    var sql3 = "update reply set content=?,replyUserId=?,replyUserNickename=? where id=? and replyUserId=?";
    var addSqlParams3 = [content, userinfo['id'], userinfo['nickname'], id, userinfo['id']];
    var result = await queryDatabase(sql3, addSqlParams3);
    
    res.send(retsuccess(''));
});

server.get('/reply/delete', async (req, res) => {
    res.header('Server', 'nodejs-restify')
    res.header('Content-Type', 'text/html');
    var params = querystring.parse(req.getQuery());
    
    var id = params.id;
    var sessionId = params.sessionId;
    
    var sql1 = "select id,username,nickname,addTime,sessionId from user where sessionId='"+sessionId+"'";
    var results = await queryDatabase(sql1);
    var userinfo = results[0];
    
    var sql1 = "select id,content,replyUserId,replyUserNickename,addTime,contentId from reply where id="+id;
    var results = await queryDatabase(sql1);
    var replyinfo = results[0];
    
    var sql2 = "update content set replyNum=replyNum-1 where id=?";
    var addSqlParams2 = [replyinfo['contentId']];
    var result = await queryDatabase(sql2, addSqlParams2);
    
    var sql3 = "update reply set isDel=1 where id=? and replyUserId=?";
    var addSqlParams3 = [id, userinfo['id']];
    var result = await queryDatabase(sql3, addSqlParams3);
    
    res.send(retsuccess(''));
});

server.listen(1102,()=>{
    console.log('%s listening at %s', server.name, server.url);
});

 

输出:

D:\workspace\studys\study_bbs>D:\software\nodejs\node.exe D:\workspace\studys\study_bbs\start_web_restify.js
(node:18764) [DEP0111] DeprecationWarning: Access to process.binding('http_parser') is deprecated.
(Use `node --trace-deprecation ...` to show where the warning was created)
restify listening at http://[::]:1102

 

标签:nodejs,res,sessionId,params,userinfo,restify,var,bbs,id
From: https://www.cnblogs.com/xuxiaobo/p/18392650

相关文章

  • 一个练习项目,好玩的bbs-nodejs-fastify
    代码:constfastify=require("fastify")();constmd5=require('md5');constquerystring=require('querystring');//npminstallfastifyvarsecretKey='saacac3423@21212';varpagesize=20;varmysql=req......
  • 一个练习项目,好玩的bbs-go-iris
    代码:packagemain/**goenv-wGO111MODULE=ongoenv-wGOPROXY=https://goproxy.cngomodinitgosgomodtidygomodvendor*/import("crypto/md5""database/sql""fmt""log""math"......
  • 一个练习项目,好玩的bbs-go-echo
    代码:packagemain/**goenv-wGO111MODULE=ongoenv-wGOPROXY=https://goproxy.cngomodinitgosgomodtidygomodvendor*/import("crypto/md5""database/sql""fmt""log""math"......
  • 一个练习项目,好玩的bbs-go-beego
    代码:packagemain/**goenv-wGO111MODULE=ongoenv-wGOPROXY=https://goproxy.cngomodinitgosgomodtidygomodvendor*/import("crypto/md5""database/sql""fmt""log""math"......
  • 一个练习项目,好玩的bbs-go-chi
    代码:packagemain/**goenv-wGO111MODULE=ongoenv-wGOPROXY=https://goproxy.cngomodinitgosgomodtidygomodvendor*/import("crypto/md5""database/sql""encoding/json""fmt""......
  • 一个练习项目,好玩的bbs-perl-mojolicious
    代码:#!D:/software/Strawberry/perl/bin/perl.exeBEGIN{push(@INC,'D:/workspace/studys/study_bbs');}useMojolicious::Lite-signatures;useutf8;useNet::MySQL;useEncode;usePOSIX;useJSONqw/encode_jsondecode_json/;useDigest;o......
  • 一个练习项目,好玩的bbs-perl-dancer
    代码:#!D:/software/Strawberry/perl/bin/perl.exeBEGIN{push(@INC,'D:/workspace/studys/study_bbs');}useutf8;useDancer;useDancer::Serializer::JSON;useNet::MySQL;useEncode;usePOSIX;useJSONqw/encode_jsondecode_json/;useDi......
  • 一个练习项目,好玩的bbs-python-cherrypy
    代码:importcherrypyimportMySQLdbimportjsonimporthashlibimportrandomimportmathimportosfromdatetimeimportdatetimeclassDateEncoder(json.JSONEncoder):defdefault(self,obj):ifisinstance(obj,datetime):returnobj......
  • 一个练习项目,好玩的bbs-python-tornado
    代码:importos.pathimporttornado.httpserverimporttornado.webimporttornado.optionsimporttornado.ioloopfromtornado.optionsimportdefine,optionsimportMySQLdbimportjsonimporthashlibimportrandomimportmathimportosfromdatetimeimportda......
  • 一个练习项目,好玩的bbs-python-flask
    代码:fromflaskimportFlask,make_response,requestimportos.pathimportMySQLdbimportjsonimporthashlibimportrandomimportmathimportosfromdatetimeimportdatetimeapp=Flask(__name__)classDateEncoder(json.JSONEncoder):defdefault(se......