-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
85 lines (77 loc) · 2.54 KB
/
index.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
77
78
79
80
81
82
83
84
85
var https = require("https");
const Koa = require('koa');
var bodyParser = require('koa-bodyparser');
const axios = require('axios');
const app = new Koa();
var util = require("./util");
var db = require('./mysql.js');
const agent = new https.Agent({
rejectUnauthorized: false
})
const instance = axios.create({ httpsAgent: agent });
app.use(bodyParser());
app.use(async (ctx, next) => {
await next();
const rt = ctx.response.get('X-Response-Time');
console.log(`${ctx.method} ${ctx.url} - ${rt}`);
// await next();
});
app.use(async (ctx, next) => {
ctx.set('Access-Control-Allow-Origin', 'http://localhost:3000');
ctx.set('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, X-Auth-Token,append,delete,entries,foreach,get,has,keys,set,values,Authorization');
ctx.set('Access-Control-Allow-Methods', 'POST, GET, PUT, DELETE, OPTIONS');
ctx.set('Connection', 'Keep-Alive');
ctx.set('Access-Control-Allow-Credentials', 'true');
await next();
});
// RewriteEngine On
// RewriteCond %{REQUEST_METHOD} OPTIONS
// RewriteRule ^(.*)$ $1 [R=200,L]
app.use(async ctx => {
if (ctx.url === "/") {
ctx.body = "hello world";
}
else if (ctx.path ==="/login" && ctx.method==="GET") {
await db.login(ctx.query)
.then((userInfo)=>{
console.log(userInfo);
ctx.body = userInfo[0];
}).catch((err)=>{
ctx.body = err;
})
} else if (ctx.path === "/view" && ctx.method==="GET") {
console.log(ctx.query);
await db.view(ctx.query)
.then((userInfo)=>{
console.log(userInfo);
ctx.body = userInfo[0];
}).catch((err)=>{
ctx.body = err;
})
} else if (ctx.path === "/edit"&& ctx.method==="POST") {
console.log(ctx.request.body);
await db.update(ctx.request.body)
.then((msg)=> {
ctx.body = msg;
}).catch((err)=> {
ctx.body = err;
});
} else if (ctx.path === "/register"&& ctx.method==="POST") {
console.log(ctx.request.body);
await db.register(ctx.request.body)
.then((msg)=> {
ctx.body = msg;
}).catch((err)=> {
ctx.body = err;
});
} else if (ctx.method==="OPTIONS" && (ctx.path === "/register" || ctx.path === "/edit")) {
ctx.status = 200;
}
});
app.on('error', err => {
log.error('server error', err)
});
app.listen(3001, function(){
console.log("server starts at localhost:3001");
db.startServer();
});