0.0.10 • Published 9 months ago

miniprogram-request-fetch v0.0.10

Weekly downloads
-
License
MIT
Repository
-
Last release
9 months ago

miniprogram-request-fetch

NPM version NPM downloads

小程序 http 请求工具

Usage

TODO

Options

TODO

Development

基本用法

import { request, extend } from 'miniprogram-request-fetch';




// get请求
const getData = (data) => {
  return request
    .get('/user', {
      data,
    })
    .then((res) => {
      return res.data;
    });
};

//post请求
const getData = (data) => {
  return request
    .post('/user', {
      data,
    })
    .then((res) => {
      return res.data;
    });
};

// 自定义
const getData = (data) => {
  return request('/user', {
    // method:'GET'
    method: 'POST',
    data,
  }).then((res) => {
    return res.data;
  });
};

//错误处理
const getData = (data) => {
  return request('/user', {
    data,
    errorHandler: (error) => {
        const codeMap = {
          'request:fail ': '请求响应错误',
          'request:fail timeout': '请求响应超时',
          // ....
        };
        error.errMsg &&
          wx.showToast({
            title: codeMap[error.errMsg] || error.errMsg,
            icon: 'error',
          });
        throw error; //抛出错误,如果不抛出请求将会转为成功
      };
  }).then((res) => {
    return {
      list: res.list,
      total: res.pagination.totalCount,
    };
  });
};

请求拦截器

// 发送请求时请求头携带token
request.interceptors.request.use((url, options) => {
  options.header.token = wx.getStorageSync('token');
  return {
    url,
    options,
  };
});

响应来拦截器

request.interceptors.response.use((res, options) => {
  return res.data;
});

使用中间件

// 实现请求前加载功能
request.use(async (context, next) => {
  //请求前
  wx.showLoading({
    title: '加载中',
  });
  try {
    await next();
    //请求后
  } catch (error) {
    throw error;
  } finally {
    wx.hideLoading();
  }
});

//使用中间件对请求前后做处理
request.use(async (ctx, next) => {
  const { req } = ctx;
  const { url, options } = req;
  // 判断是否需要添加前缀,如果是统一添加可通过 prefix、suffix 参数配置
  if (url.indexOf('/api') !== 0) {
    ctx.req.url = `/api/v1/${url}`;
  }
  ctx.req.options = {
    ...options,
    foo: 'foo',
  };

  await next();

  const { res } = ctx;
  const { success = false } = res; // 假设返回结果为 : { success: false, errorCode: 'B001' }
  if (!success) {
    // 对异常情况做对应处理
  }
});
//有些通用的配置我们不想每个请求里都去添加,那么可以通过 extend 新建一个 request 实例

import { extend } from 'miniprogram-request-fetch';

const request = extend({
  header: {
    token: wx.getStorageSync('token'),
  },
  errorHandler(error) {
    //全局错误处理
    throw error;
  },

  timeout: 300,
});

request
  .get('/user')
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

LICENSE

MIT

0.0.10

9 months ago

0.0.9

10 months ago

0.0.7

10 months ago

0.0.6

11 months ago

0.0.5

11 months ago

0.0.3

11 months ago

0.0.2

11 months ago

0.0.1

11 months ago