-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path01http.js
More file actions
33 lines (30 loc) · 1.19 KB
/
01http.js
File metadata and controls
33 lines (30 loc) · 1.19 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
var http = require("http");
//1,通过http.createServer()创建一个服务,得到一个server实例对象
// 对于服务端三件事
// 1,接受请求
// 2,处理请求
// 3,发送响应
var server = http.createServer()
//设置请求处理函数
//请求处理函数需要接受两个参数
// Request是一个请求对象,可以拿到当前请求的一些信息,例如请求路径,请求方法,请求报文等
// Response是一个响应对象,可以用来给请求发送响应
var handleRequest = function(request,response ){
console.log("收到请求了");
console.log("当前请求的请求路径是:"+request.url)
response.write("hello");
response.write(" world");
//在发送数据完毕后要主动结束响应
response.end()
}
//2,通过server实例对象添加request请求事件
// 这个事件是所有请求的入口
// 任何请求都会触发该事件对应的处理函数
server.on('request',handleRequest)
//3,绑定端口号,开启服务器
// 第一个参数是绑定的端口号
// 第二个参数是可选的
// 第三个参数是用来指定成功之后的回调函数
server.listen(8899,function(){
console.log("server is running at 8899")
})