区别:
Axios是对底层网络请求API的一层封装;
fetch是对xhr的一个替代;
xhr:XMLHttpRequest
js只能使用XMLHttpRequest或者fetch发起网络请求
xhr实际与xml没有任何联系
利用xhr发送一个请求
let xhr = new XMLHttpRequest()
xhr.open('GET', '/xhr.json')
xhr.onreadystatechange = function(e) {
if(xhr.readyState ===4) {
console.log('response', xhr.response)
}
}
xhr.send()
利用fetch发送一个请求
fetch('./fetch.json', {
method: 'GET',
headers:{
'a': 1,
}
}).then(res => {
console.log('res', res)
return res.json()
}).then(data => {
console.log(data)
}).catch(e => {
console.log('error', e)
})
xhr.open()
在xhr实例生成之后调用xhr.open()
方法就可以把网络请求的请求方法和请求的目标地址给设置
三行代码发送一个请求
// 发送请求
const xhr = new XMLHttpRequest()
xhr.open('GET', '/xhr.json')
xhr.send()
// 处理数据
xhr.onreadystatechange = function(e) {
if(xhr.readyState === 4) {
const data = xhr.response
}
}
语法
xhr.open(method, url)
xhr.open(method, url, async)
xhr.open(method, url, async, user)
xhr.open(method, url, async, user, password)
`method`
要使用的HTTP方法,GET、POST、PUT、DELETE、等,对于非HTTP(s) URL被忽略
url
一个DOMString
表示要向其发送请求的URL。
async
一个可选的布尔参数,表示是否异步执行操作,默认为true
。如果为false
,send()
方法直到收到答复前不会返回。如果true
,已完成事务的通知可供事件监听器使用。如果multipart
属性为true则这个必须为true
,否则将引发异常
xhr.send()
xhr.send()
是用来发送请求体的(get请求是不会发送请求体的,即使在xhr.send()中添加了参数)
语法
XMLHttpRequest.send(body)
body
在XHR请求中要发送的数据体可以是:
- 可以为Document,在这种情况下,它在发送之前被序列化;
- 为XMLHttpRequestBodyInit,从per the Fetch spec可以是Blob、BufferSorce、FormData、URLSearchParams或者USVString对象
- null(body中没有指定值,则默认值为null)
xhr.send()会根据参数自动设置content-type类型
- 普通字符串—text/plain
- json -–application/json
xhr.onreadystatechange()
这是一个处理xhr状态变更的监听函数,xhr总共有5中状态
0 — ‘UNSENT’: xhr被创建,但没有调用open()方法
1 — ‘OPENED’: open()方法已经被调用
2 — ‘HEADERS_RECEIVED’: send()方法已经被调用,并且头部和状态已经可获得
3 — ‘LOADING’: 下载中,responseText属性已经包含部分数据
4 — ‘DONE’: 下载操作已完成
xhr.setRequestHeader()
设置http请求的头信息
xhr.getResponseHeader()
获取服务器返回的http头信息
xhr.abort()
取消xhr请求,请求取消后可以看到取消记录
xhr.response、xhr.responseType、xhr.responseUrl
都是和处理返回内容有关
- response: 服务器返回的内容
- responseType: 设置返回内容的格式,默认为text
- responseUrl: 获取到本次请求的地址
xhr.status、xhr.statusText
- xhr.status可以用来获取HTTP响应码
- xhr.statusText则是对应的响应状态信息,对应的就是HTTP响应的第一行
xhr.timeout
设置超时时间
xhr.ontimeout
设置超时函数
xhr.timeout = 2000 xhr.ontimeout = function () { console.log('超时啦') }
xhr.withCredentials
- 和跨域请求相关的属性,控制是否允许浏览器发送cookie到服务端的
- 该属性对于同域名网站没有任何作用,即页面地址和服务器地址都属于同一域名下,直接发送cookie就可以了
- 如果当前页面请求的是不同域名下的地址,设置该属性为false或者不设置的时候,发送的请求不会携带cookie,设置为true则会报错
xhr.onprogress
检测下载进度,通过loaded
和total
来计算下载进度
xhr.onprogress = function (e) {
console.log('onprogress', e)
console.log('进度', `${Math.floor(e.loaded / e.total * 100)} %`)
}
loaded:
已经下载的大小
total:
总的大小
综合实例
const xhr = new XMLHttpRequest()
xhr.open('POST', 'https://api.x.com.setUInfo')
xhr.withCredentials = true
xhr.responseType = 'json'
xhr.setRequestHeader('content-type', 'application/json')
xhr.onreadystatechange = function(e) {
if(xhr.readyState === 4) {
console.log('status', xhr.status)
console.log('statusText', xhr.statusText)
console.log('content-type', xhr.getResponseHeader('content-type'))
const data = xhr.response
// 业务逻辑
}
}
xhr.onprogress = function (e) {
console.log('onprogress', e)
// console.log('进度', `${Math.floor(e.loaded / e.total * 100)} %`)
}
xhr.timeout = 2000
xhr.ontimeout = function () {
console.log('请求超时')
}
xhr.onabort = function () {
console.log('取消请求')
}
xhr.send(JSON.stringify({
name: 'yunu',
age: 10086
}))
fetch
使用fetch发起一个网络请求是非常简单的
async function getData() {
const res = await fetch('./fetch.json')
console.log('res', res)
const data = await res.json()
console.log('data', data)
}
getData()
fetch有两个参数位,第一个参数一般是一个字符串,就是目标地址url,第二个参数是一个对象,用来添加对请求的各种配置
async function getData() {
const res = await fetch('http://xxxx.xx/xx', {
method: 'POST',
credentials: 'same-origin',
mode: 'cors',
headers: {
'content-type': 'application/json',
a: 1
},
body: JSON.stringify({
name: 'xxx',
age: 10086
})
})
console.log('res', res)
const data = await res.json()
console.log('data', data)
}
getData()
也可以创建request实例作为fetch的参数
async function getData3() {
const myRequest = new Request('./api/xxx', {
method: 'GET'.
credentials: 'omit',
headers: {
'content-type': 'application/json',
a: 1
}
})
const res = await fetch(myRequest)
console.log('res3', res)
const data = await res.json()
console.log('data3', data)
}
Request.method
http请求的 请求方法(GET POST HEAD PUT DELETE OPTIONS CONNECT TRACE), 可大写 可小写 可大小写,写错会返回错误
Request.headers
可以给headers传递一个对象,请求发起的时候会把该对象合并到HTTP的请求头里面去,重复的key会被最后出现的key覆盖掉
Request.body
body
是用来添加请求体的,和xhr.send()
相似
Request.mode
是一个枚举值,可以是以下的值
- cors 可以发起同域名和不同域名的请求,不同域名的请求必须在后台配置跨域
- navigate 和页面跳转有关
- no-cors 表示一个简单的跨域请求
- same-origin 表示发起的是一个同源请求,当前页面域名和请求的域名必须是相同的
Request.credentials
在跨域请求的时候决定是否发送cookie等信息,只有true或false两个参数
signal
和取消跨域请求相关的属性,请求取消后会抛出一个promise reject
cache
和缓存相关的配置
response
- res.status 状态码
- res.statusText 状态文本
- res.url 本次请求的目标地址
- res.headers 返回的HTTP头信息
- res.type 请求类型 basic cors
想要获取请求头信息可以通过response.headers.get()来获取
获取返回的内容
- await response.json() 返回内容时json
- await response.text()
- await response.blob()
- await response.arrayBuffer()