-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
81 lines (51 loc) · 1.49 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
77
78
79
80
81
const handleBlogRoute = require('./src/routes/blog');
const querystring = require('querystring');
const getPostData = (req)=>{
const promise = new Promise((resolve,reject)=>{
if(req.method !== 'POST'){
resolve({});
return;
}
if(req.headers['content-type'] !== 'application/json'){
resolve({});
return;
}
let postData = '';
req.on('data',(chunk)=>{
postData += chunk.toString();
});
req.on('end',()=>{
if(!postData){
resolve({});
return;
}
resolve(
JSON.parse(postData)
);
})
});
return promise;
}
const serverHandler = (req,res) =>{
res.setHeader('Content-Type','application/json');
const url = req.url;
req.path = url.split('?')[0];
req.query = querystring.parse(url.split('?')[1]);
getPostData(req).then((postData)=>{
//博客相关的路由
req.body = postData;
const blogDataPromise = handleBlogRoute(req,res);
if(blogDataPromise){
blogDataPromise.then(blogData=>{
res.end(
JSON.stringify(blogData)
)
});
return;
}
res.writeHead(404, {'Content-Type': 'text/plain'});
res.write('404 Not Found');
res.end();
})
}
module.exports = serverHandler;