uni-http

在uniapp中发送请求和上传文件的api进行了封装

Usage no npm install needed!

<script type="module">
  import uniHttp from 'https://cdn.skypack.dev/uni-http';
</script>

README

uniapp中使用http发送请求和上传文件

install

$ npm i uni-http

Get

import { UniHttp } from 'uni-http';

const api = new UniHttp({
  baseURL: 'http://localhost:3000'
});

const res = await api.get('/api/hello', {
  params: { name: 'ajanuw' },
  header: { 'x-id': 1 }
});

// or

const res = await api.get({
  url: '/api/hello',
  params: { name: 'ajanuw' },
  header: { 'x-id': 1 }
});

Post

import { UniHttp } from 'uni-http';

const api = new UniHttp({
  baseURL: 'http://localhost:3000',
  header: {
    'Content-Type': 'application/x-www-form-urlencoded'
  },
});

await api.post('/api/login', {
  data: {
    name: 'ajanuw'
  }
});

使用拦截器

class MyInterceptors {
  request(options) {
    options.header['x-token'] = 'xxxyyy';
    uni.showLoading();
  }
  complete(result, options) {
    uni.hideLoading();
  }
}

const api = new UniHttp({
  baseURL: 'http://localhost:3000',
  interceptors: [new MyInterceptors()]
});

拦截器类型

type OrPromise<T> = T | Promise<T>;
type C = IUniHttpConfig;
type RSCR = UniApp.RequestSuccessCallbackResult;
type GCR = UniApp.GeneralCallbackResult;

export interface UniHttpInterceptors {
  /**
   * 发送前拦截
   */
  request?: (options: C) => void;

  /**
   * 在success拦截
   */
  success?: (result: RSCR, options: C) => OrPromise<RSCR>;

  /**
   * 在fail拦截
   */
  fail?: (result: GCR, options: C) => void;

  /**
   * 在complete拦截
   */
  complete?: (result: GCR, options: C) => void;
}

上传文件

uni.chooseImage({
  success: async chooseImageRes => {
    const tempFilePaths = chooseImageRes.tempFilePaths;

    const r = await api.post('/api/upload', {
      name: 'file',
      filePath: tempFilePaths[0],
      data: {
        name: 'ajanuw'
      }
    });

  }
});

在h5上跨域,你可能需要设置一个拦截器

class MyInterceptors {
  request(options) {
    // #ifdef H5
    if(process.env.NODE_ENV === 'development') options.baseURL = '';
    // #endif
  }
}

const api = new UniHttp({
  baseURL: 'http://xxx.fun/',
  interceptors: [new MyInterceptors()]
});

manifest.json:

  "h5": {
    "devServer": {
      "https": false,
      "proxy": {
        "/api": {
          "target": "http://xxx.fun/",
          "changeOrigin": true,
          "secure": false
        }
      }
    }
  }

中断请求

import { UniHttp, UniHttpInterceptors, UniAbortController } from 'uni-http';

class MyInterceptors {
  fail(result) {
    if (result.errMsg === 'request:fail abort') {
      console.log('请求被中断')
    }
    return result;
  }
}

const api = new UniHttp({
  baseURL: 'http://xxx.fun/',
  interceptors: [new MyInterceptors()]
});

const abortController = new UniAbortController();

api.get('/api/cats', {
  abortController: abortController,
}).then(console.log)

// 中断请求
abortController.abort();

在请求发送前结束请求

class MyInterceptors {
  request(options) {
    // 将cancel设置为true,请求将不会发送
    // 并且会调用拦截器的fail和complete
    options.cancel = true;
  }

  fail(result) {
    // { errMsg: "request:fail cancel" }
  }
}

See also: