-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
69 lines (54 loc) · 1.44 KB
/
app.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
import Koa from 'koa'
import http from 'http'
import bodyParser from 'koa-bodyparser'
import koaStatic from 'koa-static'
import path from 'path'
import pool from './src/utils/mysql'
import Result from './src/utils/result'
import router from './src/main'
import { verifyToken } from './src/utils/jwt'
import { io } from './src/socket/index'
import config from './config.json'
const app = new Koa()
app.use(bodyParser())
app.use(new Result().callback())
app.use(
koaStatic(path.resolve(__dirname, '../public'))
)
// 挂载数据库连接池
app.use(async (ctx, next) => {
ctx.pool = pool
await next()
})
app.use(async (ctx, next) => {
try {
await next();
} catch (err) {
console.log(err);
ctx.fail(err.message || '服务器出现错误!', err)
}
})
const WHITE_URL = ['/user/login', '/user/register', '/isProduction']
app.use(async (ctx, next) => {
// await next()
// return
let index = WHITE_URL.indexOf(ctx.path)
if (index > -1) {
await next()
return;
}
let token = ctx.header['token'];
const userData = verifyToken(token);
if (userData) {
ctx.userData = userData;
await next();
} else {
ctx.fail('用户信息验证失败!')
}
})
app.use(router.routes()) // 安装主路由
app.use(router.allowedMethods())
const server = http.createServer(app.callback());
/** socket部分 */
io.attach(server)
server.listen(config.port, () => console.log(`远程地址:http://localhost:${config.port}/`))