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

news/2024/11/15 16:27:35/文章来源:https://www.cnblogs.com/xuxiaobo/p/18392652

代码:

const fastify = require("fastify")();
const md5 = require('md5');
const querystring = require('querystring');//npm install fastifyvar 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);});});
}fastify.get("/", (req, res) => {res.header('Server', 'nodejs-fastify')res.header('Content-Type', 'text/html');res.send("此站接口使用nodejs-fastify实现,<a href='api.html' target='_blank'>接口列表</a>");
});fastify.get('/user/register', async (req, res) => {res.header('Server', 'nodejs-fastify')res.header('Content-Type', 'text/html');var username = req.query.username;var nickname = req.query.nickname;var password = req.query.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, '用户名已经存在'));}
});fastify.get('/user/login', async (req, res) => {res.header('Server', 'nodejs-fastify')res.header('Content-Type', 'text/html');var username = req.query.username;var password = req.query.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, '用户名或者密码错误'));}
});fastify.get('/user/logout', async (req, res) => {res.header('Server', 'nodejs-fastify')res.header('Content-Type', 'text/html');var sessionId = req.query.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));
});fastify.get('/user/getuserinfo', async (req, res) => {res.header('Server', 'nodejs-fastify')res.header('Content-Type', 'text/html');var sessionId = req.query.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));
});fastify.get('/post/list', async (req, res) => {res.header('Server', 'nodejs-fastify')res.header('Content-Type', 'text/html');var page = req.query.page;var keyword = req.query.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}));
});fastify.get('/post/detail', async (req, res) => {res.header('Server', 'nodejs-fastify')res.header('Content-Type', 'text/html');var id = req.query.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]));
});fastify.get('/post/add', async (req, res) => {res.header('Server', 'nodejs-fastify')res.header('Content-Type', 'text/html');var title = req.query.title;var content = req.query.content;var sessionId = req.query.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));
});fastify.get('/post/edit', async (req, res) => {res.header('Server', 'nodejs-fastify')res.header('Content-Type', 'text/html');var id = req.query.id;var title = req.query.title;var content = req.query.content;var sessionId = req.query.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(''));
});fastify.get('/post/delete', async (req, res) => {res.header('Server', 'nodejs-fastify')res.header('Content-Type', 'text/html');var id = req.query.id;var sessionId = req.query.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(''));
});fastify.get('/reply/list', async (req, res) => {res.header('Server', 'nodejs-fastify')res.header('Content-Type', 'text/html');var page = req.query.page;var contentId = req.query.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}));
});fastify.get('/reply/detail', async (req, res) => {res.header('Server', 'nodejs-fastify')res.header('Content-Type', 'text/html');var id = req.query.id;var sql1 = "id,content,replyUserId,replyUserNickename,addTime from reply where id="+id;var results = await queryDatabase(sql1);res.send(retsuccess(results[0]));
});fastify.get('/reply/add', async (req, res) => {res.header('Server', 'nodejs-fastify')res.header('Content-Type', 'text/html');var contentId = req.query.contentId;var content = req.query.content;var sessionId = req.query.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));
});fastify.get('/reply/edit', async (req, res) => {res.header('Server', 'nodejs-fastify')res.header('Content-Type', 'text/html');var id = req.query.id;var content = req.query.content;var sessionId = req.query.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(''));
});fastify.get('/reply/delete', async (req, res) => {res.header('Server', 'nodejs-fastify')res.header('Content-Type', 'text/html');var id = req.query.id;var sessionId = req.query.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(''));
});fastify.listen(1103, (err) => {if (err) throw err;console.log("Server is running on http://localhost:1103");
});

 

输出:

D:\workspace\studys\study_bbs>D:\software\nodejs\node.exe D:\workspace\studys\study_bbs\start_web_fastify.js
(node:9488) [FSTDEP011] DeprecationWarning: Variadic listen method is deprecated. Please use ".listen(optionsObject)" instead. The variadic signature will be removed in `fastify@5`.
(Use `node --trace-deprecation ...` to show where the warning was created)
Server is running on http://localhost:1103

 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.hqwc.cn/news/791025.html

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

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

代码:const express = require(express); const app = express(); const md5 = require(md5);//npm install expressvar secretKey = saacac3423@21212; var pagesize = 20;var mysql = require(mysql); var connection = mysql.createConnection({host : 127.0.0.1,…

查看linux邮件/patch

事情的起因是发现 gpio_request 被标记成弃用了,想找一下改这个patch和邮件,查看一下原因。 首先 # gpiolib-legacy.c是该函数存在的文件 git blame drivers/gpio/gpiolib-legacy.c然后得到该change的commit git show f402886得到了该commit的标题,如红框所示。 最后在这个网…

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

代码:const Koa = require(koa); const Router = require(koa-router); const md5 = require(md5);//npm install koa koa-routerconst app = new Koa(); const router = new Router();var secretKey = saacac3423@21212; var pagesize = 20;var mysql = require(mysql);…

NocoBase 与百事通:为法律行业带来全新变革

百事通使用 NocoBase 优化法律案件处理,实现案件数据的批量管理、复杂工作流的自动化和基于角色的权限定制。这些改进简化了操作,大大提高案件处理效率。关于百事通 上海百事通信息技术股份有限公司成立于 2006 年,是大型创新型法律服务提供方,构建了法律数字化智能平台,为…

一个练习项目,好玩的bbs-perl-dancer

代码:#! D:/software/Strawberry/perl/bin/perl.exeBEGIN {push (@INC,D:/workspace/studys/study_bbs); }use utf8; use Dancer; use Dancer::Serializer::JSON; use Net::MySQL; use Encode; use POSIX; use JSON qw/encode_json decode_json/; use Digest;our $pagesize = …

一个练习项目,好玩的bbs-go-beego

代码:package main/** go env -w GO111MODULE=on go env -w GOPROXY=https://goproxy.cn go mod init gos go mod tidy go mod vendor */import ("crypto/md5""database/sql""fmt""log""math""strconv""git…

一个练习项目,好玩的bbs-python-webpy

代码:import web import os.path import MySQLdb import json import hashlib import random import math import os from datetime import datetimeclass DateEncoder(json.JSONEncoder):def default(self, obj):if isinstance(obj, datetime):return obj.strftime("%Y-…

一个练习项目,好玩的bbs-python-flask

代码:from flask import Flask, make_response, request import os.path import MySQLdb import json import hashlib import random import math import os from datetime import datetimeapp = Flask(__name__)class DateEncoder(json.JSONEncoder):def default(self, obj):…

新电脑第一次拉取仓库代码

为确保你提交的代码身份被 Gitee 正确识别,请执行以下命令完成配置git config --global user.name xxxxxxxx git config --global user.email xxxxxxxx初次使用 SSH 协议进行代码克隆、推送等操作时,需按下述提示完成 SSH 配置1 生成 RSA 密钥ssh-keygen -t rsa2 获取 RSA 公…

java~重写hashcode和equals

单字段和多字段重写hashcode 在 Java 中,重写 hashCode 方法的场景通常与对象的哈希值计算有关,特别是在使用哈希表(如 HashMap, HashSet 等)时。下面是你提供的两种 hashCode 实现的具体使用场景分析: 1. 第一种实现 @Override public boolean equals(Object o) {if (thi…

鱼眼相机成像模型和畸变模型

一文详解分析鱼眼相机投影成像模型和畸变模型 - feng..liu - 博客园 (cnblogs.com) 深入洞察OpenCV鱼眼模型之成像投影和畸变表估计系数相互转化 - 知乎 (zhihu.com)