Fetch接口请求

1.npm安装cnpm install --save isomorphic-fetch es6-promise
2.由于ie不支持Promise,所以需要安装promise-polyfill;

cnpm install promise-polyfill --save-exact

3.需要在index.js中引用

import Promise from "promise-polyfill";
if(!window.Promise){
window.Promise = Promise;
}

4.配置文件封装

//前置拼接url
let api = '域名地址';

//处理promise和fetch的兼容性以及引入
require('es6-promise').polyfill();
require('isomorphic-fetch');

//处理get请求,传入参数对象拼接
let formatUrl = obj => {
  let params = Object.values(obj).reduce((a, b, i) => `${a}${Object.keys(obj)[i]}=${b}&`, '?');
  return params.substring(0, params.length - 1);
};

let Fetch = (url, option = {}) => {
  option.headers = option.headers || {};
  // option.headers['pl'] = 'admin';
  // option.headers['token'] = `${window.localStorage.getItem('token')}`; //是否使用headers带去token等参数
  const m = (option.method || '').toLocaleLowerCase();
  // get query format
  if (m == 'get') {
    if (option.query) {
      url = url + formatUrl(option.query);
    }
  }
  //对非get类请求头和请求体做处理
  if (m === 'post' || m === 'put' || m === 'delete') {
    option.headers['Content-Type'] = option.headers['Content-Type'] || 'application/json';
    option.body = JSON.stringify(option.body);
    // option.body = qs.stringify(option.body) //根据后台要求,如果有时候是java请求会用qs转
  }
  return new Promise((resolve, reject) => {
    fetch(api + url, option)
      .then(response => {
        status = response.status;
        if (response.status >= 500) {
          Fetch.systemError && Fetch.systemError('系统错误');
        }
        return response;
      })
      .then(parseJSON)
      .then(response => {
        response.status = status;
        if (response.status >= 401) {
          if (response.state == 8888) {
            //登陆超时返回状态吗

            Fetch.overTime && Fetch.overTime(response);
          }
          if (response.state == 6666) {
            //没有权限返回状态码
          }
        }
        resolve(response);
      })
      .catch(error => {
        console.log('err', error);
        Fetch.otherError && Fetch.otherError(error.message);
      });
  });
};

//response 转化
function parseJSON(response) {
  return response.json();
}

export default Fetch;

5…请求使用

async ApiFetchlist(e){
        let query={id:e};//参数
        let reslist = await this.Fetch('logic/apply/getGoods', {
          method: 'get',
          query
        });
        // console.log(reslist);
        this.morelist = reslist.data;
      }

注意在使用async及await是要注意一起使用

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值