-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
62 lines (53 loc) · 1.48 KB
/
app.js
File metadata and controls
62 lines (53 loc) · 1.48 KB
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
const querystring = require('querystring');
const handleBlogRouter = require('./src/router/blog');
const handleUserRouter = require('./src/router/user');
const getPostData = (req) => {
const promise = new Promise((resolve, reject) => {
if (req.method !== 'POST') {
resolve({});
} else if (req.headers['content-type'] !== 'application/json') {
resolve({});
} else {
let postData = '';
req.on('data', (chunk) => {
postData += chunk.toString();
});
req.on('end', () => {
if (!postData) {
resolve({});
} else {
resolve(JSON.parse(postData));
}
});
}
});
return promise;
};
const serverHandle = (req, res) => {
const url = req.url;
req.path = url.split('?')[0];
req.query = querystring.parse(url.split('?')[1]);
res.setHeader('Content-type', 'application/json');
getPostData(req).then((postData) => {
req.body = postData;
// 处理 blog 路由
const blogDataResult = handleBlogRouter(req, res);
if (blogDataResult) {
blogDataResult.then((blogData) => {
res.end(JSON.stringify(blogData));
});
return;
}
// 处理 user 路由
const userData = handleUserRouter(req, res);
if (userData) {
res.end(JSON.stringify(userData));
return;
}
// 未命中路由,返回 404
res.writeHead(404, { 'Content-type': 'text/plain' });
res.write('404 Not Found');
res.end();
});
};
module.exports = serverHandle;