-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
73 lines (61 loc) · 2.35 KB
/
server.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
const express = require('express')
const bodyParser = require('body-parser')
const fs = require('fs')
const path = require('path')
const compression = require('compression')
const app = express()
// gzip
app.use(compression());
// CORS & Preflight request
app.use((req, res, next) => {
if (req.path !== '/' && !req.path.includes('.')) {
res.set({
'Access-Control-Allow-Credentials': true,
'Access-Control-Allow-Origin': req.headers.origin || '*',
'Access-Control-Allow-Headers': 'X-Requested-With,Content-Type',
'Access-Control-Allow-Methods': 'PUT,POST,GET,DELETE,OPTIONS',
'Content-Type': 'application/json; charset=utf-8',
'Content-Security-Policy': 'upgrade-insecure-requests'
})
res.type('json')
}
req.method === 'OPTIONS' ? res.status(204).end() : next()
})
// cookie parser
app.use((req, res, next) => {
req.cookies = {}, (req.headers.cookie || '').split(/\s*;\s*/).forEach(pair => {
let crack = pair.indexOf('=')
if (crack < 1 || crack == pair.length - 1) return
req.cookies[decodeURIComponent(pair.slice(0, crack)).trim()] = decodeURIComponent(pair.slice(crack + 1)).trim()
})
next()
})
// body parser
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: false }))
// app.use('/', (req, res, next) => {
// console.log(req.originalUrl, req.query, req.body)
// next()
// })
fs.readdirSync(path.join(__dirname, 'api')).reverse().forEach(file => {
if (!file.endsWith('.js')) return
let route = '/' + file.replace(/\.js$/i, '').replace(/_/g, '/')
let question = require(path.join(__dirname, 'api', file))
app.use(route, (req, res) => {
let body = Object.assign({}, req.query, req.body, { cookie: req.cookies })
question(body, (answer) => {
console.log('[OK]', decodeURIComponent(req.originalUrl))
// res.append('Set-Cookie', answer.cookie)
res.status(answer.status).send(answer.body)
}, (err) => {
console.log('[ERR]', decodeURIComponent(req.originalUrl))
res.status(500).send(err)
})
})
})
const port = process.env.PORT || 3000
const host = process.env.HOST || ''
app.server = app.listen(port, host, () => {
console.log(`server running @ http://${host ? host : 'localhost'}:${port}`)
})
module.exports = app