react-native fetch 请求封装
2023-09-11 14:15:30 时间
1.fetch 函数封装
fetch.js
/** * 请求头 * @type {{Accept: string, Content-Type: string}} */ const header = { 'Accept': 'application/json', 'Content-Type': 'application/json', }; /** * 注意这个方法前面有async关键字 * @param url 请求地址 * @param body 请求参数 * @param method 请求方法 大写 * @param successCallBack 网络请求成功的回调 * @param errorCallBack 出错的回调 * @returns {Promise.<*>} */ export function requestUrl(url, method, body, successCallBack: func, errorCallBack: func) { if ('GET' === method) { get(url, body, successCallBack, errorCallBack); } else { post(url, body, successCallBack, errorCallBack); } } /** * get请求 */ async function get(url, body, successCallBack, errorCallBack) { let str = toQueryString(body); if (str && str.length > 0) url += '?' + str; console.log(url); try { // 注意这里的await语句,其所在的函数必须有async关键字声明 let response = await fetch(url); console.log('reqyestUrl:' + url); let responseJson = await response.json(); return successCallBack(responseJson); } catch (error) { return errorCallBack(error); //console.error(error); } } /** * post请求 */ async function post(url, body, successCallBack, errorCallBack) { try { // 注意这里的await语句,其所在的函数必须有async关键字声明 let response = await fetch(url, { method: 'POST', headers: header, body: JSON.stringify(body) }); console.log('reqyestUrl:' + url); let responseJson = await response.json(); return successCallBack(responseJson); } catch (error) { return errorCallBack(error); } } /** * 用于对对象编码以便进行传输 * @param obj 对象参数 * @returns {string} 返回字符串 */ function toQueryString(obj) { let str = ''; if (obj) { let keys = []; for (let key in obj) { keys.push(key); } keys.forEach((key, index) => { str += key + '=' + obj[key]; if (index !== keys.length - 1) { str += '&'; } }); } return str; }
.
相关文章
- docker容器封装redis 挖矿病毒kdevtmpfs的处理
- react开发教程(六)React与DOM
- AVAudioPlayer简易封装
- 服务器设计笔记(1)-----消息的封装
- 第一百四十节,JavaScript,封装库--浏览器检测
- [React] Override webpack config for create-react-app without ejection
- [React Intl] Render Content with Markup Using react-intl FormattedHTMLMessage
- [React] Create a Virtualized List with Auto Sizing Cells using react-virtualized and CellMeasurer
- [React] Use react styled system with styled components
- [React] Ensure all React useEffect Effects Run Synchronously in Tests with react-testing-library
- [React Intl] Render Content Based on a Number using react-intl FormattedMessage (plural)
- [React Intl] Format a Date Relative to the Current Date Using react-intl FormattedRelative
- [React Intl] Format Date and Time Using react-intl FormattedDate and FormattedTime
- [React Intl] Install and Configure the Entry Point of react-intl
- CSV和集合对象基于Annotation操作封装
- python封装特性详解及入门代码示例
- C#.NET万能数据库访问封装类(ACCESS、SQLServer、Oracle)
- atitit.React 优缺点 相比angular react是最靠谱的web ui组件化方案了
- mysqli 封装
- 操作系统的概述 并发和共享的关系 任务管理器 系统资源 向上层提供服务 GUI 封装思想 联机命令 脱机命令 操作系统的特征 并行 并发 共享 虚拟 异步 总结 新手上车 言简意赅 通俗易懂
- 【taro react】 ---- Stepper 步进器组件封装