fetch:
是一種HTTP數(shù)據(jù)請(qǐng)求的方式坛缕,是XMLHttpRequest的一種替代方案。fetch不是ajax的進(jìn)一步封裝捆昏,而是原生js赚楚。Fetch函數(shù)就是原生js,沒(méi)有使用XMLHttpRequest對(duì)象骗卜。
具體fetch內(nèi)容:
http://undefinedblog.com/window-fetch-is-not-as-good-as-you-imagined/?utm_source=caibaojian.com
缺點(diǎn):
- fetch只對(duì)網(wǎng)絡(luò)請(qǐng)求報(bào)錯(cuò)宠页,對(duì)400,500都當(dāng)做成功的請(qǐng)求寇仓,需要封裝去處理
- fetch對(duì)請(qǐng)求回來(lái)的json格式是ReadableStream流的形式举户。
- fetch默認(rèn)不會(huì)帶cookie,需要添加配置項(xiàng)fetch(url, {credentials: 'include'})
- fetch不支持abort遍烦,不支持超時(shí)控制俭嘁,使用setTimeout及Promise.reject的實(shí)現(xiàn)的超時(shí)控制并不能阻止請(qǐng)求過(guò)程繼續(xù)在后臺(tái)運(yùn)行,造成了流量的浪費(fèi)
- fetch沒(méi)有辦法原生監(jiān)測(cè)請(qǐng)求的進(jìn)度服猪,而XHR可以
- 所有版本的 IE 均不支持原生 Fetch兄淫,fetch-ie8 會(huì)自動(dòng)使用 XHR 做 polyfill屯远。但在跨域時(shí)有個(gè)問(wèn)題需要處理。IE8, 9 的 XHR 不支持 CORS 跨域捕虽,不支持傳 Cookie慨丐!所以推薦使用 fetch-jsonp
fetch封裝:
export default async(url = '', data = {}, type = 'GET', method = 'fetch') => {
type = type.toUpperCase();
url = baseUrl + url;
if (type == 'GET') {
let dataStr = ''; //數(shù)據(jù)拼接字符串
Object.keys(data).forEach(key => {
dataStr += key + '=' + data[key] + '&';
})
if (dataStr !== '') {
dataStr = dataStr.substr(0, dataStr.lastIndexOf('&'));
url = url + '?' + dataStr;
}
}
if (window.fetch && method == 'fetch') {
let requestConfig = {
credentials: 'include',//為了在當(dāng)前域名內(nèi)自動(dòng)發(fā)送 cookie , 必須提供這個(gè)選項(xiàng)
method: type,
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
mode: "cors",//請(qǐng)求的模式
cache: "force-cache"
}
if (type == 'POST') {
Object.defineProperty(requestConfig, 'body', {
value: JSON.stringify(data)
})
}
try {
const response = await fetch(url, requestConfig);
const responseJson = await response.json();
return responseJson
} catch (error) {
throw new Error(error)
}
} else { //ajax+promise
return new Promise((resolve, reject) => {
let requestObj;
if (window.XMLHttpRequest) {
requestObj = new XMLHttpRequest();
} else {
requestObj = new ActiveXObject;
}
let sendData = '';
if (type == 'POST') {
sendData = JSON.stringify(data);
}
requestObj.open(type, url, true);
requestObj.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
requestObj.send(sendData);
requestObj.onreadystatechange = () => {
if (requestObj.readyState == 4) {
if (requestObj.status == 200) {
let obj = requestObj.response
if (typeof obj !== 'object') {
obj = JSON.parse(obj);
}
resolve(obj)
} else {
reject(requestObj)
}
}
}
})
}
}
axios:
具體點(diǎn):中文:https://www.kancloud.cn/yunye/axios/234845
官方:http://www.axios-js.com/docs/
- 從 node.js 創(chuàng)建 http 請(qǐng)求
- 支持 Promise API
- 客戶(hù)端支持防止CSRF(請(qǐng)求中攜帶cookie)
- 提供了一些并發(fā)請(qǐng)求的接口(重要泄私,方便了很多的操作)
- 豐富的api, Interceptors, 并發(fā):
1)各種ajax的api別名房揭,
axios.request(config)
axios.get(url[, config])
axios.delete(url[, config])
axios.head(url[, config])
axios.post(url[, data[, config]])
axios.put(url[, data[, config]])
axios.patch(url[, data[, config]])
const axios = require('axios');
// Make a request for a user with a given ID
axios.get('/user?ID=12345')
.then(function (response) {
// handle success
console.log(response);
})
.catch(function (error) {
// handle error
console.log(error);
})
.then(function () {
// always executed
});
// Optionally the request above could also be done as
axios.get('/user', {
params: {
ID: 12345
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
})
.then(function () {
// always executed
});
// Want to use async/await? Add the `async` keyword to your outer function/method.
async function getUser() {
try {
const response = await axios.get('/user?ID=12345');
console.log(response);
} catch (error) {
console.error(error);
}
}
2)創(chuàng)建實(shí)例,還有一些實(shí)例方法
axios.create([config])
var instance = axios.create({
baseURL: 'https://some-domain.com/api/',
timeout: 1000,
headers: {'X-Custom-Header': 'foobar'}
});
實(shí)例方法:
axios#request(config)
axios#get(url[, config])
axios#delete(url[, config])
axios#head(url[, config])
axios#post(url[, data[, config]])
axios#put(url[, data[, config]])
axios#patch(url[, data[, config]])
3)處理并發(fā)請(qǐng)求的助手函數(shù):
a. axios.all(iterable)
b. axios.spread(callback)
4)攔截器:
// 添加請(qǐng)求攔截器
axios.interceptors.request.use(function (config) {
// 在發(fā)送請(qǐng)求之前做些什么
return config;
}, function (error) {
// 對(duì)請(qǐng)求錯(cuò)誤做些什么
return Promise.reject(error);
});
// 添加響應(yīng)攔截器
axios.interceptors.response.use(function (response) {
// 對(duì)響應(yīng)數(shù)據(jù)做點(diǎn)什么
return response;
}, function (error) {
// 對(duì)響應(yīng)錯(cuò)誤做點(diǎn)什么
return Promise.reject(error);
});