Skip to content

Commit 4cc7723

Browse files
committed
使用Node搭建简单的http服务器
1 parent d19ceec commit 4cc7723

4 files changed

Lines changed: 100 additions & 0 deletions

File tree

‎Node/Node学习笔记.md‎

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
### 用Post请求创建资源
2+
3+
```javascript
4+
http.createServer(function(req,res){
5+
req.on("data",function(data){
6+
console.log("parsed",data);
7+
});
8+
req.on("end",function(){
9+
console.log("done parse!");
10+
res.end();
11+
});
12+
}).listen(3000,function(){
13+
console.log("server is runing...");
14+
})
15+
```
16+
17+
默认情况下data事件返回的是Buffer对象,这是Node版的字节数组,也就是二进制数据,
18+
19+
如果需要字符串,则需要使用utf8编码
20+
21+
`req.setEncoding("uft8")`
22+
23+
可以通过`req.method`获的请求类型
24+
25+
- Get
26+
- Post
27+
- Put
28+
- Delete
29+
30+
为了提高响应的速度,可以带着`Content-Lenght`一并发送,响应主体在内存中提前构建好,使用Content-Length,会默认禁用Node的块编码,从而提高速度
31+
32+
**注**.Content-Lenght不是字符串的长度,而是字符串所占的字节数,字节长度,不是字符长度
33+
34+
**正确**:`var content-length=Buffer.byteLength(str);`
35+
36+
**错误**:`var content-length=str.length;`
37+
38+
39+

‎Node/http服务器/server.js‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
let http=require("http");
2+
http.createServer(function(req,res){
3+
var body=`
4+
<form>
5+
<input type="input">
6+
<select>
7+
<option>中国</option>
8+
<option>美国</option>
9+
</select>
10+
</form>`;
11+
res.setHeader("Content-Type","text/html;charset=utf-8");
12+
res.setHeader("Content-Length",body.length);
13+
res.statusCode=200;
14+
res.end(body);
15+
}).listen(3000,function(){
16+
console.log("server is runing...");
17+
})

‎Node/http服务器/server2.js‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
var http=require("http");
2+
3+
http.createServer(function(req,res){
4+
req.setEncoding("utf8");
5+
req.on("data",function(data){
6+
console.log(data);
7+
});
8+
req.on("end",function(){
9+
console.log("done parse!");
10+
res.end();
11+
});
12+
}).listen(3000,function(){
13+
console.log("server is runing...");
14+
})

‎Node/http服务器/server3.js‎

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
var http=require("http");
2+
var items=[];
3+
http.createServer(function(req,res){
4+
switch(req.method){
5+
case "POST":
6+
var item="";
7+
req.setEncoding("utf8");
8+
req.on("data",function(chunk){
9+
item += chunk;
10+
});
11+
req.on("end",function(){
12+
items.push(item);
13+
res.end("ok!");
14+
});
15+
break;
16+
case "GET":
17+
var body=items.map(function(item,i){
18+
return `(${i}:${item})`;
19+
}).join("\n");
20+
res.writeHead(200,{
21+
"Content-Type":"text/plain;charset=utf-8",
22+
"Content-Length":Buffer.byteLength(body)
23+
});
24+
res.end(body);
25+
break;
26+
27+
}
28+
}).listen(3000,function(){
29+
console.log("server is runing...");
30+
})

0 commit comments

Comments
 (0)