Ajax、Fetch异步请求封装的工具

Fetch请求

Fetch请求是基于Promise的请求
    var fetchOption = {
      method: 'POST',
      headers: {'Accept': 'application/json', 'Content-Type': 'application/json',},
      mode: 'no-cors',
      body: JSON.stringify(params)
    }

    fetch(url, fetchOption)
      .then(response => response.json())
      .then(responseJson=> {

      }).catch(function (e) {
      console.log("error");
    });

Ajax请求

   const params = {
      card_type: values.type,
      version:values.edition,
      imgBase64:this.state.base64,
    }
   let ret = post('/platApi/system/identityCard',params);

post是来自与自己封装的ajax请求

import $ from 'jquery';
import {message} from 'antd';

export function get(url) {
  let ret = {};
  $.ajax(url, {
    type: "GET",
    async: false,
    dataType: "json",
    success: function (data, status, request) {
      ret = data;
    },
    error: function (obj, status, request) {
      message.error("获取失败["+url+"]")
    }
  });

  checkResp(url, ret);
  return ret;
}

export function post(url, param) {
  let ret = {};

  $.ajax(url, {
    type: "POST",
    async: false,
    dataType: "json",
    contentType: "application/json",
    data: JSON.stringify(param),
    success: function (data, status, request) {
      ret = data;
    },
    error: function (obj, status, request) {
      message.error("获取失败[" + url + "]")
    }
  });

  checkResp(url, ret);
  return ret;
}

export function checkResp(url, ret, title) {
  if (401 == ret.code) {
    let path = ret.url;
    window.location.href = path;
    return false;
  } else if (0 != ret.code) {
    let t = "获取失败";
    if (title) {
      t = title;
    }

    message.error(`${t}[${url}][${ret.message}]`);
    return false;
  }

  return true;
}

你可能感兴趣的:(Ajax、Fetch异步请求封装的工具)