-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
69 lines (62 loc) · 1.96 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
const path = require('path')
// 引用放在最上,避免加载顺序问题导致配置未生效
const envFile = require('./config/dotenv')
require('dotenv').config({ path: path.resolve(__dirname, envFile) })
const Koa = require('koa')
const app = new Koa()
const views = require('koa-views')
const json = require('koa-json')
const onerror = require('koa-onerror')
const bodyparser = require('koa-bodyparser')
const logger = require('koa-logger')
const helmet = require('koa-helmet')
const routers = require('./routes')
const morgan = require('koa-morgan')
const fse = require('fs-extra')
// const winston = require('winston')
const middlewares = require('./middlewares')
// error handler
onerror(app)
// middlewares
app.use(bodyparser({
enableTypes: ['json', 'form', 'text']
}))
app.use(json())
app.use(logger())
app.use(require('koa-static')(path.join(__dirname, '/public')))
app.use(views(path.join(__dirname, '/views'), {
extension: 'ejs'
}))
// winston
// const logger = winston.createLogger({
// level: 'info',
// format: winston.format.json(),
// defaultMeta: { service: 'koa-demo' },
// transports: [
// new winston.transports.File({ filename: path.join(__dirname, 'logs', 'error.log'), level: 'error' }),
// new winston.transports.File({ filename: path.join(__dirname, 'logs', 'combined.log') })
// ]
// })
// if (process.env.NODE_ENV !== 'production') {
// logger.add(new winston.transports.Console({
// format: winston.format.simple()
// }))
// }
// morgan 记录http日志
const logs = path.join(__dirname, 'logs')
fse.ensureDirSync(logs)
const accessLogStream = fse.createWriteStream(
`${logs}/access.log`, { flags: 'a' }
)
app.use(morgan('combined', { stream: accessLogStream }))
// helmet
app.use(helmet())
// 启用middlewares目录下的中间件
middlewares.initApp(app)
// routes
app.use(routers.routes(), routers.allowedMethods())
// error-handling
app.on('error', (err, ctx) => {
console.error('server error', err, ctx)
})
module.exports = app