网络协议分层
物理层:定义物理设备如何去传输数据(电脑硬件,网卡端口,网线,光缆)
数据链路层:通信的实体间建立数据链路连接(软件)
网络层:数据在结点之间传输创建逻辑链路(ip)
传输层:提供可靠的端到端(End-to-End)服务(tcp udp),传输层向高层屏蔽了数据通信的细节
应用层:为应用软件提供了很多服务
HTTP协议的发展历史
- HTTP/0.9
只有一个命令GET
没有header等描述数据的信息
服务器发送完毕,就关闭TCP连接
- HTTP/1.0
增加了很多命令
增加了status code和header
多字符集支持、多部分发送、权限、缓存等
- HTTP/1.1
持久连接 请求1->响应1->请求2->响应2->请求3->响应3
pieline(管线化) 同个连接多个请求 请求1->请求2->请求3->响应1->响应2->响应3
增加host和其他一些命令
- HTTP/2.0
所有数据以二进制传输
同一个连接里面发送多个请求不再需要按照顺序来 请求1->请求2->请求3->响应2->响应1->响应3 信道复用
头信息压缩以及推送等提高效率的功能
HTTP三次握手
http request发起会新建一个tcp connection 三次握手是为了规避网络传输过程中延时导致一些服务器开销的问题
curl baidu.com
curl www.baidu.com
curl -v www.baidu.com
HTTP报文
报文分为:请求报文
和响应报文
请求报文分为:请求行
请求头
空行
请求体
响应报文:响应行
响应头
空行
响应体
HTTP方法
HTTP Code
0 未初始化 还没有调用send方法
1 载入 已调用send方法,正在发送请求
2 载入完成 send方法执行完成,已经接受到全部响应内容
3 交互 正在解析响应内容
4 完成 响应内容解析完成,可以在客户端调用了
1xx 指示信息 表示请求已接受,继续处理
2xx 成功 表示请求已被成功接收
3xx 重定向 要完成请求必须进行更进一步的操作
4xx 客户端错误 请求有语法错误或请求无法实现
5xx 服务器错误 服务器未能实现合法的请求
const http = require('http')
const server = http.createServer(function (request, response) {
response.end('123')
})
server.listen(8888)
console.log('server listening on 8888')
CORS跨域
预请求:
允许的方法:GET
POST
HEAD
允许的Content-Type: text/plain
multipart/form-data
application/x-www-form-urlencoded
允许的headers
'Access-Control-Allow-Origin': 'http://127.0.0.1:8888'
'Access-Control-Allow-Headers': 'X-Test-Cors'
'Access-Control-Allow-Methods': 'POST, PUT, DELETE'
'Access-Control-Max-Age': '1000'
缓存
cache-control
exprises
response.writeHead(200, {
'Content-Type': 'text/javascript',
'Cache-Control': 'max-age=20'
})
Last-Modified If-Modified-Since 上次修改时间
Etag If-Non-Match 数据签名
cookie
cookie和session
cookie 通过Set-Cookie设置 下次请求自动带上
response.writeHead(200, {
'Content-Type': 'text/html',
'Set-Cookie': ['id=123; max-age=2,HttpOnly', 'abc=456;domain=test.com']
})
长连接
'Connection': 'keep-alive' // close
数据协商
response.writeHead(200, {
'Content-Type': 'text/html',
// 'X-Content-Options': 'nosniff'
'Content-Encoding': 'gzip'
})
redirect
const http = require('http')
http.createServer(function (request, response) {
console.log('request come', request.url)
if (request.url === '/') {
response.writeHead(302, { // or 301
'Location': '/new'
})
response.end()
}
if (request.url === '/new') {
response.writeHead(200, {
'Content-Type': 'text/html',
})
response.end('<div>this is content</div>')
}
}).listen(8888)
console.log('server listening on 8888')
内容安全策略 CSP Content-Sercurity-Policy
response.writeHead(200, {
'Content-Type': 'text/html',
'Content-Sercurity-Policy': 'default-src http: https:'
'Content-Sercurity-Policy': 'default-src \'self\''
})
<meta http-equiv="Content-Sercurity-Policy" content="default-src 'self'">