1.前言
上篇文章写了fetch基础配置
这篇文章写写 在项目中的简要封装 其实
vue
和react
的封装都差不多
2. 基础 api封装
src/api/fetch.js
//get请求封装 const fetchGet = function(url, params) { let list = []; for (let key in params) { let str = `${key}=${params[key]}` list.push(str); } const data = list.join('&'); let allUrl = `${url}?${data}`; // debugger return fetch(allUrl).then(res => { return res.json(); }).catch(err => { console.log(err); }); }; // post请求封装 const fetchPost = function(url, params) { let formData = new FormData(); for (let key in params) { formData.append(key, params[key]) }; return fetch(url, { body: formData, method: 'POST' }).then(res => { return res.json(); }).catch(err => { console.log(err); }) }; // 这个其实写不写都不行 const fetchAll = function(url, params, method='GET') { if (method === 'GET' || method === 'get') { return fetchGet(url, params); } return fetchPost(url, params); } export default { fetchGet, fetchPost, fetchAll }
都比较简单也没什么需要说的
3. 使用
import myFetch from '@/api/fetch.js'; onMounted(()=>{ myFetch.fetchGet("https://yzs.example.org/v1/getData",{ id:"yzs123" }).then(res => { console.log(res); }).catch(err => { console.log(err); }) })
下面的和上面的不相干 是另外一种封装方式
4. 整个的 fetch 环境配置
export default async(url = '', data = {}, type = 'GET', method = 'fetch') => { const baseUrl = "http://yzs.com" 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 { 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) } } } }) } }
5. api配置
api/getData.js
/** * 获取导航菜单 */ export const getHomeNavData = () => fetch('/v1/getData', { userId: 'yzs123456' }) /** * 获取首页列表 */ export const queryList= ( kw, type) => fetch('/v2/query',{ kw, type }, 'POST')
6. 使用
import {getHomeNavData} from 'src/service/getData' getHomeNavData (this.userId).then(res => { console.log("res",res) }) queryList("郑州加油","1",).then(res => { console.log("REs-----------:",res) })