ReactNative encapsulates fetch network requests,
ReactNative encapsulates fetch network requests
/*** // *** Request header * @ type {Accept: string, Content-Type: string} */const header = {'access ': 'application/json', 'content-type': 'application/json ',}; /*** note that the async keyword * @ param url request address * @ param body request parameter * @ param method the request method is capitalized * @ param successCallBack callback for successful network requests * @ param errorCallBack error callback * @ returns {Promise. <*>} */export function requestUrl (url, method, body, successCallBack: func, error CallBack: func) {if ('get' = method) {GET (url, body, successCallBack, errorCallBack);} else {post (url, body, successCallBack, errorCallBack) ;}}/*** get request */async function get (url, body, successCallBack, errorCallBack) {let str = toQueryString (body ); if (str & str. length> 0) url + = '? '+ Str; console. log (url); try {// note the await statement here. The function must contain the async keyword declaration 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 Request */async function post (url, body, successCallBack, errorCallBack) {try {// pay attention to the await statement, the function must contain Sync keyword declaration 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 );}} /*** encode the object for transmission * @ param obj object parameter * @ returns {string} returns the 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 ;}