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

qq-request

v1.0.1

Published

基于uni-app 的网络请求工具

Downloads

4

Readme

QQ-Request

  • 基于Promise,实现高度封装的Request请求类。
  • 支持网络请求、文件上传、文件下载。
  • 支持Task操作,可终止请求、监听上传/下载进度。
  • 支持请求/响应拦截,支持对请求参数和响应结果二次处理。
  • 支持自定义校验器,可对响应结果做校验。
  • 支持配置多个请求实例。
  • 无复杂语法,兼容性强。
  • 代码结构清晰、易懂,注释完善。

参数说明

const config = {
    // 接口域名
    host: "https://xx.com/api/",
    // 请求方法
    method: "GET",
    // 请求数据,GET时为QueryString,POST时为JSON
    data: undefined,
    // 接口数据类型
    dataType: "json",
    // 超时时间,单位毫秒
    timeout: 10000,
    // header头
    header: {},
    // 是否显示loading效果,为false时,不显示,为true时强制显示,不传时,会延迟showLoadingDelay毫秒后显示
    showLoading: undefined,
    // 延迟多长时间显示loading效果,为0时则直接显示
    showLoadingDelay: 2000,
    // 加载中文字
    loadingText: "加载中",
    // 遇到错误时是否提示
    showError: true,
    // 默认错误消息
    defaultError: "请求失败",
    // 是否对Response对象进行校验
    validate: true,
    // 是否只返回data层数据,不为true时,返回Response对象。
    brief: true,
    /**
     * 在请求前对请求参数处理
     * @param {Object} config
     * @returns {Object}
     */
    before: (config) => config,
    /**
     * 在返回promise前,对promise处理
     * @param {RequestTaskPromise} promise
     * @returns {RequestTaskPromise}
     */
    after: (promise) => promise,
    /**
     * 将响应对象转换为Response对象,默认返回JsonResponse。
     * @param {Object} response
     * @returns {Response|JsonResponse|DownloadResponse}
     */
    resolver: (response) => new JsonResponse(response),
    /**
     * 返回服务器数据
     * @param {Response|JsonResponse|Object} response
     * @returns {Object|*}
     */
    briefReturn: (response) => response.getContent(),
    /**
     * 请求处理器,默认使用uni.request。
     * @param {Object} config 请求参数
     * @returns {RequestTaskPromise}
     */
    handler: (config) => new RequestTaskPromise((resolve, reject) => uni.request({
        url: config.url,
        data: config.data,
        header: config.header,
        method: config.method,
        dataType: config.dataType,
        success: resolve,
        fail: reject
    }))
}

安装

  1. npm
npm install qq-request --save
  1. yarn
yarn add qq-request
  1. Dcloud插件市场安装 进入DCloud市场,点击下载插件或使用HBuilder导入插件。

使用实例

创建实例

import {Request} from 'qq-request';

const $request = new Request({
    host: 'https://xx.com/api/',
    // ... 其他参数参考参数说明
});

发起请求


// GET请求
const user = await $request.get('/user/get', {
    id: 1
});
console.log(user);

// POST请求
const result = await $request.post('/user/add', {
    name: 'QQ',
    age: 18
});

// 自定义请求参数
const result = await $request.post('/user/add', {
    name: 'QQ',
    age: 18
}, {
    // 不显示loading
    showLoading: false
});

返回请求Task

不使用await关键词时,将返回任务TaskPromise;

const request = $request.get('/user/get', {
    id: 1
});

// 终止请求
request.abort();

// 获取影响结果
request.then(user => {
    console.log(user);
}).catch(e => {
});

返回Response对象

默认情况下,只返回服务器响应的数据,不会返回statusCode,header等数据。可设置请求参数的brief: false,要求返回Response对象。

const response = await $request.get('/user/get', {
    id: 1
}, {
    brief: false
});

// HTTP状态码
response.getStatusCode();
// 响应数据
response.getContent();

文件上传


const upload = $request.upload('/file/upload', '/path/to/file', 'image', {
    user_id: 1
});

// 监听上传进度: `onProgressUpdate`
upload.onProgressUpdate((res) => {
    console.log(res);
});

// 中止上传
upload.abort();

// 使用await关键词,可直接获取接口返回数据
const result = await $request.upload('/file/upload', '/path/to/file', 'image', {
    user_id: 1
});
console.log(result);

文件下载

const download = $request.download('/remote/file/path');

// 监听下载进度: `onProgressUpdate`
download.onProgressUpdate((res) => {
    console.log(res);
});

// 中止下载
download.abort();

// 获取响应结果
download.then(response => {
    console.log(response.getFilePath());
});

// 使用await关键词,支持获取DownloaResponse。
const response = await $request.download('/remote/file/path');

// 获取本地文件路径
console.log(response.getFilePath());

// 打开图片预览
response.previewImage();

// 打开文档
response.openDocument();

插件扩展

扩展请求参数

const $request = new Request({
    before(config) {
        config.header['Token'] = 'xxx';

        return config;
    }
});

请求拦截

const $request = new Request({
    after(requestTaskPromise) {
        return requestTaskPromise
            .then(ret => ret)
            .catch(console.log);
    }
})

响应结果校验

const $request = new Request({
    validator(response) {
        if (response.getStatusCode() !== 200) {
            throw new Error("状态码错误");
        }
    }
})

自定义返回数据

// 自定义响应类
const $request = new Request({
    resolver(result) {
        return new JsonResponse(result);
    }
});
// 自定义返回数据
const $request = new Request({
    briefReturn(jsonResponse) {
        return jsonResponse.getData();
    }
});

自定义请求处理器

const $request = new Request({
    // 必须返回RequestTaskPromise或继承它的子类
    handler(config) {
        return new RequestTaskPromise((resolve, reject) => {
            // fetch(..).then(resolve).catch(reject);
        });
    }
});