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

standard-http-client

v1.1.0

Published

符合接口规范的 HTTP 客户端

Downloads

6

Readme

standard-http-client

NPM version Build Status Coverage Status Known Vulnerabilities changelog license

npm-image

符合接口规范的 HTTP 客户端(基于 axios)

功能

主要功能

  • 遵循接口规范, 当接口调用成功时才会执行 resolve, resolve 时可以便捷地获取到接口规范中的业务数据
  • 规范化请求的错误处理, 生成标准的错误码, 并输出错误日志
    • error._desc 错误分类的描述, 例如: 接口调用出错
    • error._errorType 错误分类, 例如: H
    • error._errorNumber 错误编号, 例如: 404
    • error._errorCode 错误码, 例如: H404
  • 预留扩展机制, 便于实现定制需求(例如统一开启/关闭 loading)

次要功能

  • 扩展 axios 的配置项 _jsonp: 通过 JSONP 机制发送请求, 并支持和 axios 兼容的参数和拦截器
  • 扩展 axios 的配置项 _data: 实现类似 jQuery.ajax 的 data 配置项机制
    • GET 请求时, 适配到 axios 的 params 配置项上
    • POST/PUT/PATCH 请求时, 将对象转成 form-urlencoded 的字符串, 适配到 axios 的 data 配置项上
    • PS: 针对其他情况, 例如需要传 JSON 数据时, 请使用 axios 原有的 data 配置项
  • 扩展 axios 的配置项 _interceptDuplicateRequest: 可拦截重复请求

示例

发送请求

import StandardHttpClient from 'standard-http-client';

var httpClient = new StandardHttpClient({ // instance axios Request Config
    withCredentials: true,
    timeout: 10000
});

httpClient.send({ // axios Request Config
    url: 'https://domain.com/path/to/api'
}).then(function([data, response]) {
    // 注意: 这里的 data 是接口规范中的 data 字段, 即接口返回的业务数据
    console.log(data);
});

httpClient.send({
    url: 'https://domain.com/path/to/api',
    // 拦截重复请求
    _interceptDuplicateRequest: true
}).then(function([data, response]) {
    console.log(data);
});

// 通过 JSONP 发送请求
httpClient.send({
    url: 'https://domain.com/path/to/api',
    _jsonp: true
}).then(function([data, response]) {
    console.log(data);
});

// 通过 _data 发送数据更便捷
httpClient.send({
    url: 'https://domain.com/path/to/api',
    _data: {
        foo: 'bar'
    }
}).then(function([data, response]) {
    console.log(data);
});

// 如果调用的接口不符合接口规范, 可以通过 transformResponse 机制适配接口数据以符合接口规范
httpClient.send({
    url: 'https://domain.com/path/to/api',
    transformResponse: [function(data) {
        // 注意这里的 data 是原始数据, 即大部分情况都是 string 类型
        // axios 默认的 transformResponse 是对 data 做了 JSON.parse
        var _data = JSON.parse(data);

        var standardData = {
            status: 0,
            data: null,
            statusInfo: {
                message: '',
                detail: ''
            }
        };

        standardData.status = _data.code;
        standardData.data = _data.res;
        standardData.statusInfo.message = _data.message;

        return standardData;
    }]
}).then(function([data, response]) {
    console.log(data);
});

hook 机制

import StandardHttpClient from 'standard-http-client';

class HttpClient extends StandardHttpClient {
    constructor(config) {
        super(config);
    }

    beforeSend(config) {
        console.log('before send', config);
    }
    afterSend(responseOrError) {
        console.log('after send', responseOrError);
    }
    handleError(error) {
        console.log('handle error', error);
    }
}

var httpClient = new HttpClient({ // instance axios Request Config
    withCredentials: true,
    timeout: 10000
});

httpClient.send({ // axios Request Config
    url: 'https://domain.com/path/to/api'
}).then(function([data, response]) {
    console.log(data);
});

参考实现: shc-pc

扩展拦截器

import StandardHttpClient from 'standard-http-client';

class HttpClient extends StandardHttpClient {
    constructor(config) {
        super(config);
    }
    useInterceptors() {
        super.useInterceptors();

        // this.agent is an instance of axios
        this.agent.interceptors.request.use(function(config) {
            console.log('HttpClient request config', config);
            return config;
        }, function (error) {
            console.log('HttpClient request error', error);
            return Promise.reject(error);
        });

        this.agent.interceptors.response.use(function(response) {
            console.log('HttpClient response', response);
            return response;
        }, function(error) {
            console.log('HttpClient response error', error);
            return Promise.reject(error);
        });
    }
}

var httpClient = new HttpClient({ // instance axios Request Config
    withCredentials: true,
    timeout: 10000
});

httpClient.send({ // axios Request Config
    url: 'https://domain.com/path/to/api'
}).then(function([data, response]) {
    console.log(data);
});

详见 API 文档