Skip to content

Commit

Permalink
💘chore:升级服务端版本
Browse files Browse the repository at this point in the history
  • Loading branch information
durunsong committed Nov 26, 2024
1 parent 57398c4 commit fcfc745
Show file tree
Hide file tree
Showing 14 changed files with 517 additions and 54 deletions.
5 changes: 3 additions & 2 deletions server/.env
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
# 这里放置一些配置信息
PORT = 4000
# JWT 刷新令牌KEY
# 端口号
PORT = '4000'
# JWT_SECRET --- 用于生成和验证JWT的密钥
JWT_SECRET = 'f7d623cd21149c493d7304960edaf2e10ad147528dbaf183520184fc0a0f64cb'
83 changes: 83 additions & 0 deletions server/app.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
/**
* 引入模块依赖
*/
const app = require("./bin/index");
const debug = require("debug")("kilyicms_server:server");
const http = require("http");

/**
* 从环境变量中获取端口号,如果未定义则使用默认端口 4000
*/
const port = normalizePort(process.env.PORT || "4000");
app.set("port", port);

/**
* 创建 HTTP 服务器
*/
const server = http.createServer(app);

/**
* 监听指定端口,启动服务器
*/
server.listen(port, () => {
console.log(`Server is running on port ${port}`);
});
server.on("error", onError);
server.on("listening", onListening);

/**
* 将端口规范化为数字、字符串或 false
* @param {string|number} val - 输入的端口值
* @returns {number|string|boolean} - 规范化后的端口
*/
function normalizePort(val) {
const port = parseInt(val, 10);
// 检查是否为有效端口号
if (isNaN(port)) {
// 不是数字则返回原始字符串(如命名管道)
return val;
}
if (port >= 0) {
// 有效端口号
return port;
}
return false; // 无效端口
}

/**
* 处理服务器启动过程中的错误
* @param {Error} error - 错误对象
*/
function onError(error) {
if (error.syscall !== "listen") {
throw error;
}
const bind = typeof port === "string" ? "Pipe " + port : "Port " + port;
// 用友好信息处理特定的监听错误
switch (error.code) {
case "EACCES":
console.error(bind + " requires elevated privileges");
process.exit(1);
break;
case "EADDRINUSE":
console.error(bind + " is already in use");
process.exit(1);
break;
default:
throw error;
}
}

/**
* HTTP 服务器 “监听 ”事件的事件监听器。
*/
function onListening() {
const addr = server.address();
const bind = typeof addr === "string" ? "pipe " + addr : "port " + addr.port;
debug("Listening on " + bind);
}

/**
* @vercel部署需要这样写
*/
module.exports = app;
49 changes: 49 additions & 0 deletions server/bin/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
// 入口文件
require("dotenv").config();
const createError = require("http-errors");
const express = require("express");
const bodyParserMiddleware = require("../middleware/bodyParserMiddleware");
const corsMiddleware = require("../middleware/corsMiddleware");
const userRoutes = require("../routes/userRoutes");
const { connectDb } = require("../config/db-connection");
const path = require("path");
// const { hashExistingPasswords } = require("./controllers/hashExistingPasswords");

// 创建服务器对象
const app = express();

// 在服务器启动时,调用 hashExistingPasswords 函数
// 备用方案, 如果需要加密所有用户密码,则取消注释
// hashExistingPasswords();

// 加载中间件
app.use(bodyParserMiddleware.json); // 使用 bodyParser.json()
app.use(bodyParserMiddleware.urlencoded); // 使用 bodyParser.urlencoded()
app.use(corsMiddleware); // 使用 cors()

// 设置静态资源目录
app.use(express.static(path.join(__dirname, "../public")));

// 设置视图引擎
app.set("views", path.join(__dirname, "../views"));
app.set("view engine", "ejs");

// 数据库连接
connectDb();

// 注册路由
app.use("/", userRoutes);

// 处理 404 错误
app.use((req, res, next) => {
next(createError(404));
});

// 错误处理
app.use((err, req, res) => {
res.locals.message = err.message;
res.locals.error = req.app.get("env") === "development" ? err : {};
res.status(err.status || 500).render("error");
});

module.exports = app;
45 changes: 45 additions & 0 deletions server/controllers/home.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
// 默认首页
const homePage = (req, res) => {
res.send(`
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="icon" href="/images/api.png" type="image/x-icon" />
<title>kilyicms-server</title>
<style>
body {
margin: 0;
height: 100vh;
display: flex;
justify-content: center;
align-items: center;
background-color: #f4f4f9;
}
h1 {
font-size: 3rem;
font-weight: bold;
background: linear-gradient(45deg, #ff416c, #ff4b2b, #f0c27b, #4b1248);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
text-align: center;
animation: gradient 5s infinite;
}
@keyframes gradient {
0% { background-position: 0% 50%; }
50% { background-position: 100% 50%; }
100% { background-position: 0% 50%; }
}
</style>
</head>
<body>
<h1>Welcome to the world of kilyicms API!</h1>
</body>
</html>
`);
};

module.exports = {
homePage,
};
8 changes: 0 additions & 8 deletions server/controllers/login.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,38 +7,30 @@ const { connection } = require("../config/db-connection.js");

const loginUser = (req, res) => {
const { user_name, password } = req.body;

if (!user_name || !password) {
return res
.status(400)
.json({ status: 400, message: "账号和密码都是必需的" });
}

const findUserQuery =
"SELECT * FROM users WHERE user_name = ? AND is_delete = 0";

connection.query(findUserQuery, [user_name], async (err, results) => {
if (err) {
console.error(err);
return res.status(500).json({ status: 500, message: "查询用户失败" });
}

if (results.length === 0) {
return res.status(409).json({ status: 409, message: "用户不存在" });
}

const user = results[0];
const hashFromDb = user.password;

// 验证密码
const passWordMatch = await comparePassword(password, hashFromDb);
if (!passWordMatch) {
return res.status(409).json({ status: 409, message: "用户名或密码错误" });
}

// 生成 JWT
const token = generateToken({ id: user.id, user_name: user.user_name });

// 登录时间
const login_time = formatTime();
res.status(200).json({
Expand Down
31 changes: 0 additions & 31 deletions server/index.js

This file was deleted.

11 changes: 9 additions & 2 deletions server/package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "kilyicms_server",
"version": "2.0.1",
"main": "index.js",
"main": "app.js",
"description": "一个免费开源的多语言中后台管理系统基础解决方案,基于 Vue3、TypeScript、Element Plus、Pinia 和 Vite 等主流技术",
"author": {
"name": "Jack-DU",
Expand All @@ -14,16 +14,23 @@
},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node index.js"
"start": "node app.js"
},
"dependencies": {
"bcrypt": "^5.1.1",
"body-parser": "^1.20.3",
"cookie-parser": "~1.4.7",
"cors": "^2.8.5",
"debug": "~2.6.9",
"dotenv": "^16.4.5",
"ejs": "^3.1.10",
"express": "^4.21.1",
"http-errors": "~1.6.3",
"jsonwebtoken": "^9.0.2",
"moment": "^2.30.1",
"morgan": "~1.9.1",
"mysql2": "^3.11.3",
"path": "^0.12.7",
"uuid": "^10.0.0"
},
"devDependencies": {
Expand Down
Loading

0 comments on commit fcfc745

Please sign in to comment.