-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
47 lines (41 loc) · 1.35 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
const Koa = require('koa'); //引入koa框架
const bodyParser = require('koa-bodyparser')
const app = new Koa();
const https = require('https')
const ws = require('./server/webSocket')
const mongoose = require('./app/mongodb'); // 连接mongoDB数据库
const parameter = require("koa-parameter"); // 校验传参
const router = require('./app/routers/index')
const jwt = require('koa-jwt') // 鉴权
const secret = require('./config').secret // 密钥
const auth = jwt({secret})
app.use(bodyParser());
/* 当token被拦截返回401时,处理一下返回的数据
这个要放在app.use(auth)前面 */
app.use((ctx, next) => {
return next().catch((err) => {
if(err.status === 401){
ctx.status = 200;
ctx.body = {
code: 300,
message: 'token失效,请重新登录',
data: {}
}
}else{
throw err
}
})
})
// 使用unless来排除掉不需要token的接口
app.use(auth.unless({
path: [/\/user\/login/, /\/user\/register/,
/\/auth\/getCode/]
}))
app.use(router.routes(), router.allowedMethods())
app.use(parameter(app));
//app.listen()方法会返回http.Server
let env = process.env.NODE_ENV;
let server = app.listen( env == 'development' ? 3000 : 3001, () => {
console.log("现在开始监听3000端口");
})
app.wss = ws(server)