1.什么是HTTP服务?
一个网页请求,包含2次HTTP包交换:
- 浏览器向
HTTP服务器发送请求HTTP包 HTTP服务器向浏览器返回HTTP包
打开网站:
小结:
HTTP服务要做什么事情?
- 解析尽力啊的
HTTP请求报文 - 返回对应的
HTTP返回报文
2.简单实现一个HTTP服务器:
//引入nodeJS的http模块
const http = require('http');
//引入文件模块
const fs = require('fs');
http.createServer(function(request,response){
//默认会发两次,一起请求网页内容,一起请求页面图标ico
if(response.url==='/favicon.ico'){
response.writeHead(200);
response.end();
return;
}
response.writeHead(200);
//将index.html读取到,并作为response返回回去
fs.createReadStream(__dirname + '/index.html').pipe(response)
}).listen(3000)
🚀页面结果如下: