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

miniprogram-request

v5.3.0-alpha.0

Published

A better Request package for MiniProgram API

Downloads

331

Readme

miniprogram-request npm version

An axios API like Request package for MiniProgram

更好用的小程序请求库封装 小程序网络库miniprogram-network 核心库之一

API

methods:

  • request<T>(options): Promise<T>;
  • request<T>(method, action, data?, config?): Promise<T>;
  • get<T>(action, data?, config?): Promise<T>;
  • post<T>(action, data?, config?): Promise<T>;
  • put<T>(action, data?, config?): Promise<T>;
  • delete<T>(action, data?, config?): Promise<T>;
  • patch<T>(action, data?, config?): Promise<T>;
  • head<T>(action, data?, config?): Promise<T>;

options

  • [x] url 地址 required (只能请求时设置for single request)
  • [x] method 方法 (只能请求时设置for single request)
  • [x] data 数据 (只能请求时设置for single request)
  • [x] cancelToken 取消 (只能请求时设置for single request)
  • [x] onHeadersReceived 接收头响应 (只能请求时设置for single request)
  • [x] timeout 自定义超时时间ms (只能请求时设置for single request)
  • [x] responseType 返回数据类型
  • [x] headers 请求头
  • [x] params URL参数
  • [x] baseURL 根URL
  • [x] retry 重试次数
  • [x] timestamp 是否记录发送和响应时间戳
  • [x] transformSend 输入转换函数
  • [x] transformResponse 输出转换函数

Global Listeners

  • [x] onSend (before request data send & after request data transformed)
  • [x] onResponse (after request response data transformed)
  • [x] onRejected (before catch of Promise)
  • [x] onAbort
  • [x] onComplete

Usage

install

npm i miniprogram-request

quick start

import {REQUEST} from 'miniprogram-request';

// 设置全局配置,设置一次全部生效
// 设置请求根地址,可选
REQUEST.Defaults.baseURL = "https://minipgrogram.newfuture.cc/"
// 添加监听时间 可选
REQUEST.Listeners.onResponse.push(console.log); // 记录每次响应

REQUEST.get('items')
        .then(applyFunction) // 返回数据
        .catch(err=>wx.showToast({title:'数据拉取失败'}));

URL build

REQUEST.post('/items',{name:'future'})
// POST /items
// {name:"future"}

REQUEST.get('/items/{id}',{show_detail:false},{params:{id:12345}})
// GET /items/12345?show_detail=false

REQUEST.put('/items/{id}',{name:'new'},{params:{id:12345}})
// PUT /items/12345
// {name:"new"}
// --- json 序列化body


//由于小程序不支持Patch,此处使用X-HTTP-Method-Override实现Patch
//此功能需要服务器端支持
REQUEST.patch('/items/{id}',{name:'new'},{params:{id:12345}})
// POST /items/12345
// X-HTTP-Method-Override: PATCH
// {name:"new"}

TypeScript

泛型支持

// TS 类型推断
import { REQUEST, transformRequestResponseOkData } from 'miniprogram-request';

// 自动提取返回值为 2xx 时的 `response.data`
REQUEST.Defaults.transformResponse = transformRequestResponseOkData

interface Item {
    id: number,
    name: string
}

// 泛型 then的参数值类型为 Item[]
REQUEST.get<Item[]>('/items')
    .then(list => list.forEach(i => console.log(i.id + i.name)))

CancelToken (abort)

可通过cancel token 方式取消请求

import { REQUEST, CancelToken } from 'miniprogram-request';

// 创建一个 tokensource
const source = CancelToken.source();

REQUEST.get('items', { skip: 100 }, { 
    // 配置 cancelToken
    cancelToken: source.token 
});

// 需要取消操作时
source.cancel('cancel the reqeust');

configuration

修改全局配置

REQUEST.Defaults.retry = 2;//设置网络错误时重试次数

全部可配置内容

{

    /**
    * 请求的相对地址
    */
    url: string;

    /**
    * 请求方法
    * HTTP request mthod: GET POST ...
    */
    method:'OPTIONS'|'GET'|'HEAD'|'POST'|'PUT'|'DELETE'|'TRACE'|'CONNECT';

    /**
     * 请求数据
     * reqeust data
     *  * **data 数据说明:**
     *
     * 最终发送给服务器的数据是 String 类型,如果传入的 data 不是 String 类型,会被转换成 String 。转换规则如下:
     *
     * *   对于 `GET` 方法的数据,会将数据转换成 query string(encodeURIComponent(k)=encodeURIComponent(v)&encodeURIComponent(k)=encodeURIComponent(v)...)
     * *   对于 `POST` 方法且 `header['content-type']` 为 `application/json` 的数据,会对数据进行 JSON 序列化
     * *   对于 `POST` 方法且 `header['content-type']` 为 `application/x-www-form-urlencoded` 的数据,会将数据转换成 query string (encodeURIComponent(k)=encodeURIComponent(v)&encodeURIComponent(k)=encodeURIComponent(v)...)
     */
    data?: any;
    
    /**
     * 取消操作的 CancelToken 
     */
    cancelToken?: CancelToken;

    /**
     * 接收到响应头回调
     */
    onHeadersReceived?: TwxTask['onHeadersReceived'];

    /**
    * 请求的根目录
    * Base URL for request
    */
    baseURL?: string;
    
    /**
    * 自定义头 
    * user defined headers
    */
    headers?: KeyBasicValuePair;

    /**
     * URL Path
     * the path parameters to be replace in path
     * Must be a plain object
     * @example 
     *  url = "/{ID}/status"
     *  param = {ID: 12345}
     * request url will be /1234/status
     */
    params?: KeyBasicValuePair,

    /**
    * 重试次数 默认重试1次
    * retry times when fail
    */
    retry?: number; 

    /**
     * response data type
     */
    responseType?: "json" | "text" | "arraybuffer";

    /**
     * 修改数据或者头;返回 wx.request参数
     * 异步返回promise
     * You may modify the data or headers object before it is sent.
     */
    transformRequest?: (options) => PromiseOrValue<Exclude<wx.options, 'complete' | 'success' | 'fail'>>;

    /**
     * 返回数据修改,返回值作为then的输入, throw exception 抛给catch
     * 异步返回Promise
     * allows changes to the response data to be made before it is passed to then/catch
     *  @example `res=>res.data`
     */
    transformResponse?:  (res, options) => any|Promise<any>;

}

单次请求特殊配置

/每次请求全部可配置参数
//已设置的参数会覆盖默认参数
//仅对此次请求生效
REQUEST.request({
    url: 'items',
    method: 'POST',
    data: {},
    cancelToken: null,
    baseURL: 'https://qq.com/',
    headers: {},
    params: null,
    retry: 3,
    responseType: "json",
    transformRequest: Http.RequestTransformation,
    transformResponse: Http.ResponseTransformation
})

// 快速请求配置参数
REQUEST.post('items', {}, {
    //除了method,url和 data 不能设置其他均可设置
    cancelToken: null,
    baseURL: 'https://qq.com/',
    headers: {},
    params: null,
    retry: 3,
    responseType: "json",
    transformRequest: Http.RequestTransformation,
    transformResponse: Http.ResponseTransformation
})

创建一个新的Http管理对象

// 重新创建一个Http
const http = new Http({
    //除了method,url,data 和cancelToken不能设置其他均可设置
    baseURL: 'https://qq.com/',
    headers: {},
    params: null,
    retry: 3,
    responseType: "json",
    transformRequest: Http.RequestTransformation,
    transformResponse: Http.ResponseTransformation
})

LifeCircle

Request Life Circle

references