百度小程序之api封装接口,支持多个请求
- 共 3,064 次检阅

根目录创建util文件夹,新建api.js文件,内容如下

const baseUrl = '接口域名';

const http = ({ url = '', param = {}, ...other } = {}) => {
  swan.showLoading({
    title: '加载中'
  });
  let timeStart = Date.now();
  return new Promise((resolve, reject) => {
    swan.request({
      url: getUrl(url),
      // 下面data参数可用于存放接口id与接口秘钥类型等
      data: {
        "参数1": "参数值1",
        "参数2": "参数值2" ,
        "参数3": "参数值3"
      },
      header: {
        'content-type': 'application/json'
        // 默认值 ,另一种是 "content-type": "application/x-www-form-urlencoded"
      },
      ...other,
      complete: res => {
        swan.hideLoading();
        // console.log(`耗时${Date.now() - timeStart}`);
        if (res.statusCode >= 200 && res.statusCode < 300) {
          resolve(res.data);
        } else {
          reject(res);
        }
      }
    });
  });
};

const getUrl = url => {
  if (url.indexOf('://') == -1) {
    url = baseUrl + url;
  }
  return url;
};

// get方法
const get = (url, param = {}) => {
  return http({
    url,
    param
  });
};
const post = (url, param = {}) => {
  return http({
    url,
    param,
    method: 'post'
  });
};

const _put = (url, param = {}) => {
  return http({
    url,
    param,
    method: 'put'
  });
};
const _delete = (url, param = {}) => {
  return http({
    url,
    param,
    method: 'put'
  });
};

export default {
  baseUrl,
  get,
  post,
  _put,
  _delete
};

 

全局引用

import requireApi from './util/api.js';

App({
    // 添加封装标识到app
    requireApi,
    onLaunch() {
    }
});

 

使用方法:

//   单个请求
  api.requireApi.get('/journalismApi').then(res => {
    console.log(res)
  }).catch(e => {
    console.log(e)
  })
//   一个页面多个请求
  Promise.all([
    api.requireApi.get('list'),
    api.requireApi.get(`detail/${id}`)
  ]).then(result => {
    console.log(result)
  }).catch(e => {
    console.log(e)
  })

 

分享到:

这篇文章还没有评论

发表评论