5min速学fetch与XMLHttpRequest
1 关于ajax/xhr/fetch的技术说明
ajax是一种技术统称:用js语言异步的向服务器发送请求并且获取到响应结果(Asynchronous Javascript And XML)
最早实现ajax技术是微软的ie浏览器,使用XMLHttpRequest(缩写为xhr)
随着h5和es6的出现,又出现了一种实现Fetch Api
xhr和fetch都是浏览器天生对ajax的实现
另外也存在第三方库觉的原生的不好用,于是在原生的基础上自行对原生进行封装(第三方没有用新的技术,只是包了一层壳)
例如axios就是基于xhr底层或者是Node.js的http模块封装的Promise
例如jquery3.x系列的ajax依旧是基于xhr的内核
例如umi-request是一个基于axios的网络请求库
一言以蔽之,可打开最新谷歌控制台看哪些请求是用xhr写的,哪些请求是用fetch写,大家可自行看源码
下面以csdn登录页的请求为例:
可以看到,网络下的与服务器的交互方案(Asynchronous Javascript And XML)被谷歌分为了2大类,fetch/xhr
2 不废话上案例,直接贴代码
//用Fetch实现GET获取文件流(按需可添加头部信息)
fetch('https://www.baidu.com/img/PCtm_d9c8750bed0b3c7d089fa7d55720d6cf.png', {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'tk': '1'
}
}).then(response => response.blob()).then(blob => {
const url = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = 'AA.png';
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
window.URL.revokeObjectURL(url);
}).catch(error => {
console.error('下载文件时出错:', error);
});
//用xhr实现GET获取文件流(按需可添加头部信息)
var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://www.baidu.com/img/PCtm_d9c8750bed0b3c7d089fa7d55720d6cf.png', true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.setRequestHeader('tk', '1');
xhr.responseType = 'blob';
xhr.onload = function() {
if (xhr.status === 200) {
const blob = xhr.response;
const url = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = 'AA.png';
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
window.URL.revokeObjectURL(url);
} else {
console.error('下载文件时出错:', xhr.statusText);
}
};
xhr.onerror = function() {
console.error('下载文件时出错:', xhr.statusText);
};
xhr.send();
//用Fetch实现一遍POST,有header,body为json,返回也是json的demo
fetch("http://10.51.170.10:36251/demo?aa=true&bb=1500",{
"headers": {
"accept": "application/json;charset=UTF-8",
"content-type": "application/json",
},
"body": JSON.stringify({
pager:{
currentPageNum: 1,
pageSize: 20
},
queryParam:{compid: "1500"}
}),
"method": "POST",
}).then(response => response.json()).then(data => {
console.log('获得响应');
console.log(data);
}).catch(error => {
console.error('Error:', error);
});
//用XMLHttpRequest实现一遍POST
var xhr = new XMLHttpRequest();
xhr.open('POST', 'http://10.51.170.10:36251/demo?aa=true&bb=1500');
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.onload = function() {
if (xhr.status === 200) {
console.log('获得响应');
console.log(JSON.parse(xhr.responseText));
} else {
console.error('Error:', xhr.statusText);
}
};
xhr.onerror = function() {
console.error('Request failed');
};
xhr.send(JSON.stringify({
enumId: '20000695',
}));
由于是我们自己的服务,案例略
3 高阶学习,自己抓请求学习
快速复制一个请求
//复制出来是这样的
fetch("https://passport.csdn.net/v1/api/get/homeword", {
"headers": {
"accept": "application/json, text/plain, */*",
"accept-language": "zh-CN,zh;q=0.9",
"cache-control": "no-cache",
"pragma": "no-cache",
"sec-ch-ua": "\" Not A;Brand\";v=\"99\", \"Chromium\";v=\"100\", \"Google Chrome\";v=\"100\"",
"sec-ch-ua-mobile": "?0",
"sec-ch-ua-platform": "\"Windows\"",
"sec-fetch-dest": "empty",
"sec-fetch-mode": "cors",
"sec-fetch-site": "same-origin",
"x-requested-with": "XMLHttpRequest"
},
"referrer": "https://passport.csdn.net/login?code=applets",
"referrerPolicy": "unsafe-url",
"body": null,
"method": "GET",
"mode": "cors",
"credentials": "include"
});
//我们改造下 就能获取这个json了
fetch("https://passport.csdn.net/v1/api/get/homeword", {
"headers": {
"accept": "application/json, text/plain, */*",
"accept-language": "zh-CN,zh;q=0.9",
"cache-control": "no-cache",
"pragma": "no-cache",
"sec-ch-ua": "\" Not A;Brand\";v=\"99\", \"Chromium\";v=\"100\", \"Google Chrome\";v=\"100\"",
"sec-ch-ua-mobile": "?0",
"sec-ch-ua-platform": "\"Windows\"",
"sec-fetch-dest": "empty",
"sec-fetch-mode": "cors",
"sec-fetch-site": "same-origin",
"x-requested-with": "XMLHttpRequest"
},
"referrer": "https://passport.csdn.net/login?code=applets",
"referrerPolicy": "unsafe-url",
"body": null,
"method": "GET",
"mode": "cors",
"credentials": "include"
}).then(response => response.json()).then(data => {
console.log('获得响应');
console.log(data);
}).catch(error => {
console.error('Error:', error);
});
效果
后话:
** 部分网站的请求复制出来后有参数控制,不能重放,有的不能跨域执行(需要更多的跨域参数),建议各位开发者仅在自己的项目中使用这些语法,正规合法的使用这些请求