-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathparseUrl.js
57 lines (56 loc) · 1.53 KB
/
parseUrl.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
const url = require('url');
const users = [];
/**
* 解析url
* @param request
* @param response
*/
const parseUrl = (request, response) => {
const { requestUrl } = { requestUrl: url.parse(request.url, true) };
const { method } = { method: request.method };
let userName = '';
let user = '';
let requestData = '';
switch (requestUrl.pathname) {
case '/user':
switch (method) {
case 'GET':
userName = requestUrl.query.name ? requestUrl.query.name : '';
user = users.find(userItem => userItem.name === userName);
if (user) {
response.end(JSON.stringify(user));
} else {
response.end(JSON.stringify({ result: 'there isn\'t this user' }));
}
break;
case 'POST':
request.on('data', (data) => {
requestData += data.toString('utf-8');
});
request.on('end', () => {
let userStr;
try {
userStr = JSON.parse(requestData);
} catch (e) {
response.statusCode = 400;
response.end(JSON.stringify({ err: 'you sent a bad request' }));
}
users.push(userStr);
response.end(JSON.stringify({
status: 'succeed',
}));
});
break;
default:
break;
}
break;
default:
response.statusCode = 404;
response.end(JSON.stringify({
status: 'not found page',
}));
break;
}
};
module.exports = parseUrl;