1. http模块介绍
客户端与服务器的区别。
客户端:在网络节点中,负责消费资源的电脑,称之为客户端。
服务器:负责对外提供资源的电脑。
http是Node.js官方提供的,用来创建web服务器的模块,通过http.creatServer()函数,就可以把一台普通电脑变身为服务器。
2. 服务器相关概念
2.1 IP地址就是每个计算机的唯一地址,因此IP地址具有唯一性。
IP地址的格式:通常使用“点分十进制”表示(a.b.c.d)的形式。
在windows中运行
PS C:\Users\Administrator> ping www.baidu.com
正在 Ping www.a.shifen.com [112.80.248.75] 具有 32 字节的数据:
来自 112.80.248.75 的回复: 字节=32 时间=41ms TTL=54
来自 112.80.248.75 的回复: 字节=32 时间=43ms TTL=54
来自 112.80.248.75 的回复: 字节=32 时间=58ms TTL=54
来自 112.80.248.75 的回复: 字节=32 时间=40ms TTL=54
112.80.248.75 的 Ping 统计信息:
数据包: 已发送 = 4,已接收 = 4,丢失 = 0 (0% 丢失),
往返行程的估计时间(以毫秒为单位):
最短 = 40ms,最长 = 58ms,平均 = 45ms
获取了IP地址
2.2域名和域名服务器
由于IP地址是一长串的数字,不方便记忆,于是发明了域名地址的方案。
2.3端口号
计算机的端口号,就好像是现实生活中的门牌号。在一台电脑中可以运行成百上千个web服务,每个web服务都对应一个唯一的端口号。客户端发送过来的网络请求,通过端口号,可以准确地交给对应的web服务进行处理。
3.创建最基本的web服务器
const http = require('http');
const Server = http.createServer();
//绑定事件
Server.on('request', function (req, res) {
//req是请求对象,包含了与客户端相关的数据和属性
// res响应对象,包含了与服务器相关的属性和数据
console.log('Someone visit our server');
const url = req.url;
const method = req.method;
const str = `Your request url is ${url},and request method is ${method}`;
console.log(str);
res.end(str);//结束服务器
})
//启动服务器 .listen(端口号,回调函数)
Server.listen(80, function () {
console.log('http://127.0.0.1:80');
})
PS C:\Users\Administrator\Desktop\HTML\Cases> node .\05http.js
http://127.0.0.1:80 Someone visit our server Your request url is /,and
request method is GET Someone visit our server Your request url is
/favicon.ico,and request method is GET