You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

60 lines
1.5 KiB

// require('module-alias/register')
require('./global/index.js');
const Koa = require('koa');
const jwt = require('koa-jwt');
const views = require('koa-views');
const serve = require('koa-static');
const app = new Koa();
const cors = require('@koa/cors');
const koaBody = require('koa-body');
const router = require('./routes/index.js');
const config = require('./config.js');
const path = require('path')
app.use(serve(path.join(__dirname + '/public')));
app.use(views(path.join(__dirname + '/public'), {
extension: 'pug'
}));
app.use(cors());
// Custom 401 handling if you don't want to expose koa-jwt errors to users
app.use(async (ctx, next) => {
return next().catch((err) => {
if (401 == err.status) {
ctx.status = 401;
ctx.body = {
message: 'Protected resource, use Authorization header to get access\n',
data: null,
code: 401
};
} else {
throw err;
}
});
});
// https://www.v2ex.com/t/320710有关token不需要状态,可以多人登录同一个账号
app.use(jwt({
secret: config.share_key
}).unless({
path: [/^\/api\/login/, /^\/api\/register/, /^((?!\/api).)*$/,/^\/api\/menus\/getAll/]
}));
// logger
app.use(async (ctx, next) => {
const start = new Date()
await next()
const ms = new Date() - start
log(`${ctx.method} ${ctx.url} - ${ms}ms`)
});
// 请求解析
app.use(koaBody());
// 路由注册
app.use(router.routes()).use(router.allowedMethods());
// error-handling
app.on('error', (err, ctx) => {
console.error('server error', err, ctx)
});
module.exports = app