Skip to content

Commit 82cf33a

Browse files
committed
modify & add http-server code
1 parent 631c8b1 commit 82cf33a

File tree

9 files changed

+256
-46
lines changed

9 files changed

+256
-46
lines changed

17-http-server/01-method-parse.js

Lines changed: 7 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,21 @@
11
#!/usr/bin/env node
22

3-
const http = require('http');
3+
const http = require('http'),
4+
log = console.log;
5+
6+
function select(req, res) { res.end(req.method); }
7+
const insert = update = remove = select;
48

59
http.createServer((req, res) => {
6-
console.log('HTTP request method:', req.method);
10+
log('HTTP request method:', req.method);
711

812
switch(req.method) {
913
case 'GET':
1014
select(req, res);
1115
break;
1216

1317
case 'POST':
14-
create(req, res);
18+
insert(req, res);
1519
break;
1620

1721
case 'PUT':
@@ -26,19 +30,3 @@ http.createServer((req, res) => {
2630
res.end('Something Wrong!');
2731
}
2832
}).listen(8080);
29-
30-
function select(req, res) {
31-
res.end(req.method);
32-
}
33-
34-
function create(req, res) {
35-
res.end(req.method);
36-
}
37-
38-
function update(req, res) {
39-
res.end(req.method);
40-
}
41-
42-
function remove(req, res) {
43-
res.end(req.method);
44-
}

17-http-server/02-url-parse.js

Lines changed: 8 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -3,30 +3,15 @@
33
const http = require('http'),
44
log = console.log;
55

6-
print(new URL('http://wangding:[email protected]:8080/a/b/c?age=20&gender=M#/d/e/f'));
6+
const addr = new URL('http://wangding:[email protected]:8080/a/b/c?age=20&gender=M#/d/e/f');
7+
const [age, gender] = addr.searchParams.values();
78

8-
http.createServer((req, res) => {
9-
console.log('req URL:\t', req.url);
10-
11-
print(new URL(req.url, `http://${req.headers.host}`));
9+
log(addr);
10+
log(`pathname: ${addr.pathname}`);
11+
log(`age: ${age}\ngender: ${gender}`);
1212

13+
http.createServer((req, res) => {
14+
log('req URL:', req.url);
15+
log(new URL(req.url, `http://${req.headers.host}`));
1316
res.end('ok!');
1417
}).listen(8080);
15-
16-
function print(url) {
17-
log('href:\t\t', url.href);
18-
log('protocol:\t', url.protocol);
19-
log('username:\t', url.username);
20-
log('password:\t', url.password);
21-
log('hostname:\t', url.hostname);
22-
log('port:\t\t', url.port);
23-
log('host:\t\t', url.host);
24-
log('pathname:\t', url.pathname);
25-
log('search:\t\t', url.search);
26-
log('hash:\t\t', url.hash);
27-
28-
log('pathname parse:\t', url.pathname.split('/'));
29-
log('age:\t\t', url.searchParams.get('age'));
30-
log('gender:\t\t', url.searchParams.get('gender'));
31-
log();
32-
}

17-http-server/05-upload.js

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,15 +4,15 @@ const http = require('http'),
44
log = console.log;
55

66
http.createServer((req, res) => {
7+
log(`${req.method} ${req.url} HTTP/${req.httpVersion}`);
8+
log(req.headers);
9+
log('');
10+
711
if(req.url != '/') {
812
err(res);
913
return;
1014
}
1115

12-
log(`${req.method} ${req.url} HTTP/${req.httpVersion}`);
13-
log(req.headers);
14-
log('');
15-
1616
if(req.method === 'POST') {
1717
req.pipe(process.stdout);
1818
res.end('OK!');

17-http-server/13-rectangle-api.js

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
#!/usr/bin/env node
2+
3+
const http = require('http');
4+
5+
http.createServer((req, res)=>{
6+
const addr = new URL(req.url, `http://${req.headers.host}`);
7+
let [width, height] = addr.searchParams.values();
8+
[width, height] = [Number(width), Number(height)];
9+
10+
console.log(req.url);
11+
const rect = {
12+
area: width * height,
13+
perimeter: 2 * (width + height)
14+
};
15+
16+
res.setHeader('Access-Control-Allow-Origin', '*');
17+
res.end(JSON.stringify(rect));
18+
}).listen(3000);
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
#!/usr/bin/env node
2+
3+
const http = require('http'),
4+
fs = require('fs'),
5+
{join} = require('path');
6+
7+
http.createServer((req, res)=>{
8+
const addr = new URL(req.url, `http://${req.headers.host}`);
9+
if(addr.pathname == '/api') {
10+
apiServer(req, res);
11+
} else {
12+
fileServer(req, res);
13+
}
14+
}).listen(3000);
15+
16+
function fileServer(req, res) {
17+
let fileName = req.url.slice(1);
18+
fileName = join(__dirname, 'www', fileName);
19+
console.log(fileName);
20+
21+
if(!fs.existsSync(fileName)) {
22+
res.statusCode = 404;
23+
res.end(`${req.url} not found`);
24+
return;
25+
}
26+
27+
res.end(fs.readFileSync(fileName, 'utf8'));
28+
}
29+
30+
function apiServer(req, res) {
31+
const addr = new URL(req.url, `http://${req.headers.host}`);
32+
33+
let [width, height] = addr.searchParams.values();
34+
[width, height] = [Number(width), Number(height)];
35+
36+
const rect = {
37+
area: width * height,
38+
perimeter: 2 * (width + height)
39+
};
40+
41+
res.setHeader('Access-Control-Allow-Origin', '*');
42+
res.end(JSON.stringify(rect));
43+
}
Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
1+
#!/usr/bin/env node
2+
3+
const http = require('http');
4+
5+
http.createServer((req, res)=>{
6+
console.log(req.url);
7+
const addr = new URL(req.url, `http://${req.headers.host}`);
8+
console.log(addr);
9+
if(req.url == '/') {
10+
res.end(emptyPage());
11+
return;
12+
}
13+
14+
if(addr.search !== '') {
15+
res.end(resultPage(addr));
16+
return;
17+
}
18+
19+
res.end(errPage());
20+
}).listen(3000);
21+
22+
function errPage() {
23+
return '<body><h1>Not Found!</h1></body>';
24+
}
25+
26+
const html = `
27+
<!DOCTYPE html>
28+
<html lang="en">
29+
<head>
30+
<meta charset="UTF-8">
31+
<title>计算器</title>
32+
<style>
33+
span {
34+
display: inline-block;
35+
border: 1px solid black;
36+
width: 170px;
37+
height: 20px;
38+
}
39+
label {
40+
display: inline-block;
41+
width: 50px;
42+
height: 30px;
43+
}
44+
</style>
45+
</head>
46+
<body>
47+
<form method="GET" action="">
48+
<label>宽度:</label>
49+
<input type="text" name="width" value="__width"/>
50+
<br />
51+
<label>高度:</label>
52+
<input type="text" name="height" value="__height"/>
53+
<br />
54+
<label>&nbsp;</label>
55+
<input type="submit" value="计算" />
56+
<br />
57+
<label>周长:</label>
58+
<span>perimeter</span>
59+
<br />
60+
<label>面积:</label>
61+
<span>area</span>
62+
<br />
63+
</form>
64+
</body>
65+
</html>`;
66+
67+
function emptyPage() {
68+
return html.replace('area', '')
69+
.replace('perimeter', '')
70+
.replace('__width', '')
71+
.replace('__height', '');
72+
}
73+
74+
function resultPage(addr) {
75+
let [width, height] = addr.searchParams.values();
76+
[width, height] = [Number(width), Number(height)];
77+
78+
const rect = {
79+
area: width * height,
80+
perimeter: 2 * (width + height)
81+
};
82+
83+
return html.replace('area', rect.area)
84+
.replace('perimeter', rect.perimeter)
85+
.replace('__width', width)
86+
.replace('__height', height);
87+
}

17-http-server/16-weather-proxy.js

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
#!/usr/bin/env node
2+
3+
const http = require('http');
4+
5+
const cityCodes = {
6+
'北京': 101010100,
7+
'上海': 101020100,
8+
'天津': 101030100,
9+
'重庆': 101040100,
10+
'香港': 101320101,
11+
'澳门': 101330101,
12+
'石家庄': 101090101,
13+
};
14+
15+
http.createServer((req, rs)=>{
16+
const cityName = decodeURI(req.url).slice(1);
17+
const cityCode = cityCodes[cityName];
18+
const url = 'http://t.weather.sojson.com/api/weather/city/' + cityCode;
19+
20+
http.get(url, res=>{
21+
let data = '';
22+
res.on('data', chunk => data+=chunk);
23+
res.on('end', () => {
24+
rs.setHeader('Content-Type', 'text/plain; charset=utf-8');
25+
rs.end(data);
26+
});
27+
});
28+
}).listen(8080);

17-http-server/www/index.html

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
<!DOCTYPE html>
2+
<html lang="en">
3+
<head>
4+
<meta charset="UTF-8">
5+
<title>计算器</title>
6+
<style>
7+
label {
8+
display: inline-block;
9+
width: 50px;
10+
height: 30px;
11+
}
12+
</style>
13+
</head>
14+
<body>
15+
<form>
16+
<label>宽度:</label>
17+
<input type="text" name="width"/>
18+
<br />
19+
<label>高度:</label>
20+
<input type="text" name="height"/>
21+
<br />
22+
<label>&nbsp;</label>
23+
<input type="button" value="计算" />
24+
<br />
25+
<label>周长:</label>
26+
<input type="text" disabled name="perimeter" />
27+
<br />
28+
<label>面积:</label>
29+
<input type="text" disabled name="area" />
30+
<br />
31+
</form>
32+
<script src="rectangle.js"></script>
33+
</body>
34+
</html>

17-http-server/www/rectangle.js

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
/* global document: true */
2+
const q = document.querySelector,
3+
$ = q.bind(document);
4+
5+
const $width = $('input[name="width"]'),
6+
$height = $('input[name="height"]'),
7+
$btnCalc = $('input[value="计算"]'),
8+
$perimeter = $('input[name="perimeter"]'),
9+
$area = $('input[name="area"]');
10+
11+
const url = 'http://192.168.14.128:3000/api?';
12+
13+
$btnCalc.onclick = () => {
14+
const rect = {
15+
width: Number($width.value),
16+
height: Number($height.value),
17+
};
18+
19+
const qs = new URLSearchParams(rect);
20+
21+
fetch(url + qs.toString())
22+
.then(res => res.json())
23+
.then(rect => {
24+
$area.value = rect.area;
25+
$perimeter.value = rect.perimeter;
26+
});
27+
};

0 commit comments

Comments
 (0)