導讀:jquery
fetch:
這個方法是ES2017中新增的特性,這個特性出來後給人一種傳統ajax已死的感受,其實它的做用是替代瀏覽器原生的XMLHttpRequest異步請求,
咱們在平常的開發中,基本不會本身去寫XMLHttpRequest,主要是太複雜了,都是使用已經封裝好了的各類插件,經常使用的有jquery。npm包管理工具也提供了axios,request等模塊。
而有了fetch後咱們就能夠在不用這些插件的狀況下快速簡單的實現異步請求了。ios
async/await 能使得咱們在編寫異步代碼時像同步同樣的方式來編寫。具體是將異步執行的代碼封裝了或者做爲模塊導入便可。ajax
fetch.js爲封裝好的模塊,調用方式以下:npm
另起一個getData.js,用來封裝全部的Service,調用fetch。json
例 :axios
getData.js跨域
import fetch from '../config/fetch' /** * 獲取首頁默認地址 */ export const cityGuess = () => fetch('/v1/cities', { type: 'guess' }); /** * 獲取搜索地址 */ export const searchplace = (cityid, value) => fetch('/v1/pois', { type: 'search', city_id: cityid, keyword: value }); /** * 獲取msite頁面地址信息 */ export const msiteAddress = geohash => fetch('/v2/pois/' + geohash);
fetch.js瀏覽器
import { baseUrl } from './env' export default async(url = '', data = {}, type = 'GET', method = 'fetch') => { type = type.toUpperCase(); url = baseUrl + url; if (type == 'GET') { let dataStr = ''; //數據拼接字符串 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', method: type, headers: { 'Accept': 'application/json',// 用戶代理可處理的媒體類型// 用戶代理可處理的媒體類型 'Content-Type': 'application/json'// 報文主體對象類型 }, mode: "cors",// 跨域 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 { // 若是瀏覽器不支持 fetch 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) } } } }) } }