美文网首页
使用 Fetch进行http请求

使用 Fetch进行http请求

作者: 默默无闻的小人物 | 来源:发表于2021-09-29 08:20 被阅读0次
  • fetch()是 XMLHttpRequest 的升级版,用于在 JavaScript 脚本里面发出 HTTP 请求

import {
  baseUrl
} from './env'
import {
  Toast
} from 'vant';
import {
  wxLoginOAuth
} from "src/service/weiXinCommon";
import {
  loginOut,
  getToken
} from "src/service/common";

export default async (url = '', data = {}, type = 'GET', method = 'fetch') => {
  let project_token = 18031201;
  let token = getToken();
  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', 当请求的凭据模式为“include”时,响应中的标头不能是通配符“*”
      method: type,
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
        'project_token': project_token,
        'user_token': token,
      },
      //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();
      if (parseInt(responseJson.code) == 1000) { //未登录。
        const t = Toast({
          message: responseJson.info,
          duration: 2000
        });
        console.log(t);
        t.close = () => {
          //退出登录
          loginOut();
          //重定向到登录页面
          wxLoginOAuth();
        }

        return;
      }
      if (!responseJson || !responseJson.success) {
        Toast({
          message: responseJson.info,
          duration: 2000
        });
      }
      
      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/json");
      requestObj.setRequestHeader("user_token", token);
      requestObj.setRequestHeader("project_token", project_token);
      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);
            }
            if (parseInt(obj.code) == 1000) { //未登录。
              const t = Toast({
                message: obj.info,
                duration: 2000
              });
              console.log(t);
              t.close = () => {
                //退出登录
                loginOut();
                //重定向到登录页面
                wxLoginOAuth();
              }
              return;
            }
            if (!obj || !obj.success) {
              Toast({
                message: obj.info,
                duration: 2000
              });
            }
            resolve(obj)
          } else {
            reject(requestObj)
          }
        }
      }
    })
  }
}

相关文章

网友评论

      本文标题:使用 Fetch进行http请求

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