美文网首页
React Native 中的 Fetch封装

React Native 中的 Fetch封装

作者: 三文治z | 来源:发表于2019-06-25 16:09 被阅读0次

    之前做的React Native 项目使用的 Fetch封装,当初踩的坑还蛮多的...

    import { Alert, Platform } from 'react-native';
    import REQUEST from './HTTPRequest';   // 网络接口文件
    
    let HTTPBase = {};
    const REQUEST_URL = REQUEST.MAIN;
    
    /**
     * HTTP REQUEST
     * @param   {string}  $method  : GET||POST||PUT||DELETE||POSTFILE
     * @param   {string}  $url     : 接口
     * @param   {object}  $params  : {}包装 --json
     * @param   {object}  $headers : 头部信息
     * @returns {Promise}
     */
    HTTPBase.request = ($method, $url, $params, $headers) => {
      $url = REQUEST_URL + $url;
    
      $headers = $headers || {};
      $headers["Platform"] = Platform.OS;
      $headers["Version"] = global.appInfo.version_current;
      $headers["X-language"] = global.user.language;
      $headers["Accept"] = "application/json,text/plain,*/*";
      $headers["Authorization"] = "Bearer " + global.user.userToken;  // 用户的token
    
      let setting = { method: $method, headers: $headers };
    
      switch ($method) {
        case "GET":
          $headers["Content-Type"] = "application/json";
          if ($params) {
            let paramsArray = [];
            let paramsKeyArray = Object.keys($params);
            paramsKeyArray.forEach(key => paramsArray.push(key + "=" + $params[key]));
    
            //网址拼接
            if ($url.search(/\?/) === -1) {
              $url += "?" + paramsArray.join("&");
            } else {
              $url += paramsArray.join("&");
            }
          }
          break;
        
        case "POST":
        case "PUT":
        case "DELETE":
          $headers["Content-Type"] = "application/json";
          setting["body"] = JSON.stringify($params);
          break;
        // 上传文件
        case "POSTFILE":
          let formData = new FormData();
          for (let key in $params) {
            let file = {
              uri: $params[key],
              type: "application/octet-stream",
              name: $params[key].split("/")[$params[key].split("/").length - 1]
            };
            formData.append(key, file);
          }
          setting["method"] = "POST";
          setting["body"] = formData;
          break;
      }
    
      return new Promise((resolve, reject) => fetch($url, setting)
        .then(response => {
          // 提示更新app版本
          if (global.appInfo.flag == 0) {
            const version = response.headers.map.version[0];
            global.appInfo.version_latest = version;
            global.appInfo.flag = 1;  // 设置-已更新版本号
          }
          // 提示身份验证过期
          if (response.status == 401) {
            reject('登录已过期');
          } else {
            resolve(response);
          }
        })
        .catch(error => {
          reject('网络问题');
        })
        .done());
    };
    
    export default HTTPBase;
    

    相关文章

      网友评论

          本文标题:React Native 中的 Fetch封装

          本文链接:https://www.haomeiwen.com/subject/xzfxcctx.html