npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

uni-http

v0.7.8

Published

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

Downloads

47

Readme

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

install

$ npm i uni-http

基本使用

// api.js
import { UniHttp } from 'uni-http';

class Api extends UniHttp {
	config = {
		baseURL: 'https://jsonplaceholder.typicode.com',
		header: {
			'Content-Type': 'application/json'
		}
	};
	
  // 你可以在这里制作一个简易的拦截器
	request(...args) {
		console.log(args);
		return super.request(...args).then(res => res.data);
	}

	async hello() {
		return this.get("/todos/1");
	}
}

const api = new Api();

export { api };
import { api } from "api.js"
api.hello().then(data => { console.log(data); });

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/json'
  },
});

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" }
  }
}

自定义发送请求的方式

这通常在h5上很有用

const api = new UniHttp({
  baseURL: 'https://jsonplaceholder.typicode.com',

  // #ifdef H5
  async requestFunc(url, options, success, fail, complete) {
    // console.log(url,options,success,fail,complete);
    try {
      const res = await fetch(url)
      const d = await res.json();
      success(d);
      complete(d);
    } catch (e) {
      fail(e)
    }
  },
  // #endif
  
});

await api.get('/todos/1').then(res => {
  console.log(res);
});

See also: