这是我参与「第五届青训营 」伴学笔记创作活动的第 5 天 本节课主要是针对之前HTTP两节课的基础和场景进行实战分析,使用xhr和fetch作为请求连接的手段,并详解了浏览器端和node端不同的方案,同时考虑到了用户体验。
浏览器
1. XHR(XMLHttpRequest)
定义:xhr对象用于与服务器进行交互。通过xhr可以在不刷新页面的情况下请求特定的URL,获取数据。
下面是一个创建xhr并获取数据的过程
function xhr(url, method) {
const promise = new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest()
xhr.open(method, url, true)
xhr.onreadystatechange = () => {
if (this.readyState !== 4) return
if (this.status === 200) {
resolve(this.response)
} else {
reject(new Error(this.statusText))
}
}
xhr.onerror = () => {
reject(new Error(this.statusText))
}
// xhr.responseType = "json"
// xhr.setRequestHeader('Accept', 'application/json')
xhr.send()
})
return promise
}
2. Fetch
特点:
- XHR的升级版
- 使用Promise
- 模块化设计,Response,Request,Header对象
- 通过数据流处理对象,支持分块读取
function getData(url, data) {
return fetch(url, {
body: JSON.stringify(data),
cache: 'no-cache',
credentials: 'same-origin',
headers: {
'user-agent': 'Chrome 103.110.0',
'content-type': 'application/json'
},
method: 'POST',
mode: 'cors',
redirect: 'follow',
referrer: 'no-referrer'
})
.then(res => res.json())
}
getData('http://www.example/qa', {answer: 44})
.then(data => console.log(data))
.catch(error => console.log(error))
node
标准库:HTTP/HTTPS
- 默认模块,无需安装其他依赖
- 功能有限/不是十分友好
常用请求库:axios
- 支持浏览器、nodejs环境
- 丰富的拦截器
实战-用户体验
- 网络优化
- http2
- CDN动态加速
- DNS预解析
- 网络预连接
- 域名
- 压缩
- https性能优化
- 稳定性
- 重试机制(超时、错误)
- 缓存
- 数据安全 (dns劫持、http劫持)
扩展
WebSocket
- 浏览器与服务器进行全双工通讯的网络技术
- 典型场景:实时性要求高,例如聊天室
- URL使用 ws:// 或 wss:// 等开头
QUIC(udp替代tcp)
- 0-RTT建立连接
- 类似tcp的可靠传输
- 类似tls的加密传输,支持完美前向安全
- 用户控件的拥塞控制,最新的bbr算法
- 支持h2的基于流的多路复用,但没有tcp的hol问题
- 前向纠错fec
- 类似mptcp的Connection migration
QUIC协议主要是用在http3中。