forked from axios/axios
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
72 lines (61 loc) · 1.63 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
var fs = require('fs');
var url = require('url');
var path = require('path');
var http = require('http');
var server;
function pipeFileToResponse(res, file, type) {
if (type) {
res.writeHead(200, {
'Content-Type': type
});
}
fs.createReadStream(path.join(__dirname, file)).pipe(res);
}
server = http.createServer(function (req, res) {
req.setEncoding('utf8');
var parsed = url.parse(req.url, true);
var pathname = parsed.pathname;
console.log('[' + new Date() + ']', req.method, pathname);
if (pathname === '/') {
pathname = '/index.html';
}
if (pathname === '/index.html') {
pipeFileToResponse(res, './client.html');
} else if (pathname === '/axios.js') {
pipeFileToResponse(res, '../dist/axios.js', 'text/javascript');
} else if (pathname === '/axios.map') {
pipeFileToResponse(res, '../dist/axios.map', 'text/javascript');
} else if (pathname === '/api') {
var status;
var result;
var data = '';
req.on('data', function (chunk) {
data += chunk;
});
req.on('end', function () {
try {
status = 200;
result = {
url: req.url,
data: data ? JSON.parse(data) : undefined,
method: req.method,
headers: req.headers
};
} catch (e) {
console.error('Error:', e.message);
status = 400;
result = {
error: e.message
};
}
res.writeHead(status, {
'Content-Type': 'application/json'
});
res.end(JSON.stringify(result));
});
} else {
res.writeHead(404);
res.end('<h1>404 Not Found</h1>');
}
});
server.listen(3000);