This repository has been archived by the owner on Aug 30, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 58
/
index.js
89 lines (78 loc) · 1.91 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
require("dotenv").config();
const Koa = require("koa");
const bodyParser = require("koa-bodyparser");
const cors = require("koa2-cors");
const serve = require("koa-static");
const views = require("koa-views");
const app = new Koa();
const net = require("net");
const router = require("./routes");
// 配置信息
let domain = process.env.ALLOWED_DOMAIN || "*";
let port = process.env.PORT || 5678;
// 解析请求体
app.use(bodyParser());
// 静态文件目录
app.use(serve(__dirname + "/public"));
app.use(views(__dirname + "/public"));
// 跨域
app.use(
cors({
origin: domain,
})
);
app.use(async (ctx, next) => {
if (domain === "*") {
await next();
} else {
if (ctx.headers.origin === domain || ctx.headers.referer === domain) {
await next();
} else {
ctx.status = 403;
ctx.body = {
code: 403,
message: "请通过正确的域名访问",
};
}
}
});
// 使用路由中间件
app.use(router.routes());
app.use(router.allowedMethods());
// 启动应用程序并监听端口
const startApp = (port) => {
app.listen(port, () => {
console.log(`成功在 ${port} 端口上运行`);
});
};
// 检测端口是否被占用
const checkPort = (port) => {
return new Promise((resolve, reject) => {
const server = net
.createServer()
.once("error", (err) => {
if (err.code === "EADDRINUSE") {
console.log(`端口 ${port} 已被占用, 正在尝试其他端口...`);
server.close();
resolve(false);
} else {
reject(err);
}
})
.once("listening", () => {
server.close();
resolve(true);
})
.listen(port);
});
};
// 尝试启动应用程序
const tryStartApp = async (port) => {
let isPortAvailable = await checkPort(port);
while (!isPortAvailable) {
port++;
isPortAvailable = await checkPort(port);
}
startApp(port);
};
tryStartApp(port);