-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
76 lines (66 loc) · 2.15 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
70
71
72
73
74
75
76
const config = require('./config')
const app = new (require('koa'))()
const json = require('koa-json')
const jwt = require('koa-jwt');
const logger = require('koa-logger')
// const cors = require('kcors')
const cors = require('koa2-cors')
// const convert = require('koa-convert')
const uaParser = require('ua-parser-js')
const router = require('./routes.js')
app.use(require('koa-bodyparser')())
app.use(async ({request, response, url}, next) => {
let start = new Date()
await next()
let ms = new Date() - start
const ua = uaParser(request.header['user-agent'])
console.log('%s %s[%s] %s - %sms | browser: %s %s | engine: %s %s | OS: %s %s',
request.header.host, request.method, response.status, url, ms,
ua.browser.name, ua.browser.version,
ua.engine.name, ua.engine.version,
ua.os.name, ua.os.version)
})
app.use(async (ctx, next) => {
try {
await next()
} catch (err) {
if (401 == err.status) {
ctx.status = 401
ctx.body = {
success: false,
token: null,
info: 'Protected resource, use Authorization header to get access'
}
} else {
throw err
}
}
})
app.on('error', (err, ctx) => {
console.log('server serror!', err)
})
// app.use(async (ctx, next) => {
// ctx.set('Access-Control-Allow-Origin', '*')
// ctx.set('Access-Control-Allow-Methods', 'POST,GET,OPTIONS,PUT,DELETE,HEAD')
// ctx.set('Access-Control-Allow-Headers', 'Content-Type,Authorization,X-Requested-With,emulateJSON,crossOrigin')
// ctx.set('Access-Control-Allow-Credentials', true)
// ctx.set('Access-Control-Max-Age', 86400)
// await next()
// })
app.use(cors({
origin: ({ request }) =>
config.allowOrigin.includes('*') &&
'*' ||
config.allowOrigin.includes(request.header.origin) &&
request.header.origin,
allowMethods: config.allowMethods,
allowHeaders: config.allowHeaders,
maxAge: config.maxAge,
credentials: config.credentials
}))
// app.use(jwt({ secret: 'koa-test' }))
app.use(router.routes())
app.listen(config.port, () => {
console.log(`server create at http://localhost:${config.port}`)
})
module.exports = app