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

gent-request

v1.0.9

Published

固定格式的请求API

Downloads

33

Readme

gent-request

封装一个统一格式、便于使用的 http api 请求客户端类.

依赖环境

  • ES6:Class、Promise

安装使用

安装:

npm i gent-request -S

node端使用:

const Request = require('gent-request/request');

浏览器使用, 需要Promise ployfill:

import Request from 'gent-request';

初始化一个api实例

// node:
const Request = require('gent-request/request');

const api = new Request(globalOptions);

接口: 都返回promsie对象

  • api.get(url, opts={}): get请求
  • api.cacheGet(url, opts={}): 带缓存的get请求,参数一样的请求会缓存,下一次直接返回
  • api.json(url, data={}, opts={}): 提交json
  • api.form(url, data={}, opts={}): 提交form表单
  • api.formData(url, data={}, opts={}): 上传文件
  • api.download(url, opts={}): 下载(nodejs)
  • api.downloadStream(url, opts={}): 流式下载(nodejs)

options

初始化api时的全局设置:globalOptions, 或者每个方法单独设置:opts, opts覆盖globalOptions中相同的值。

可配置项如下:

{
  // 接口基础地址
  baseURL: '',
  // 返回数据格式:json, stream, other...
  responseType: 'json',
  // 超时时间
  timeout: 10000,
  // method, `api.json, api.form, api.formData` 默认为post,其他默认get
  method: 'get',
  // url 参数
  params: {},
  // headers
  headers: {},
  // timeout
  timeout: 1000,
  // 返回格式
  responseType: 'json',
  // Basic auth
  // This will set an `Authorization` header, overwriting any existing
  // `Authorization` custom headers you have set using `headers`.
  auth: {
    username: 'janedoe',
    password: 's00pers3cret'
  },
  // 验证状态码,通过视为请求无异常
  validateStatus(status) {
    return status >= 200 && status < 300;
  },
  // 请求发送前对配置进行修改,比如改headers等
  onRequest(opts) {
    return opts;
  },
  // 数据正常时统一处理,可以返回一个 Promise.reject() 转为异常状态
  onSuccess(data) {
    return data;
  },
  // 数据异常统一处理,可以返回一个 Promise.resolve() 转为正常状态
  onError(error) {
    return Promise.reject(error);
  }
}

返回结果格式

api.get('/url')
  .then(result => {
    console.log(result.data)
  })
  .catch(error => {
    console.log(error.message)
  });

// result, error:
{
  // status code 状态码, 没有 response 时为 -1
  status: 200,

  // 错误提示消息
  message: 'OK',

  // 数据,只有 `resolve` 时存在
  data: null,

  // 头部信息, 有 `response` 是存在,否则为空对象 `{}`
  headers: {},

  // 错误详情, 只有 `reject` 时存在
  error: {
    // 标识各种错误类型,便于调试、定位错误
    type: 'NO_RESPONSE',

    // 错误详情,用于服务端使用 `status code` 标识错误,同时用 `response body` 输出错误详情
    info: {code: 500},
  },

  // 请求相关信息
  info: {
    baseURL: '',
    url: ''
    method: '',
    params: {},
    data: {},
    responseType: ''
  }
}

上传文件formdata

浏览器端使用[FormData](https://developer.mozilla.org/zh-CN/docs/Web/API/FormData/Using_FormData_Objects) api:

// JavaScript file-like 对象
var content = '<a id="a"><b id="b">hey!</b></a>'; // 新文件的正文...
var blob = new Blob([content], { type: "text/xml"});

// send with FormData instance
var formData = new FormData();

formData.append("username", "Groucho");
formData.append("accountnum", 123456); // 数字 123456 会被立即转换成字符串 "123456"

// HTML 文件类型input,由用户选择
formData.append("userfile", fileInputElement.files[0]);
formData.append("webmasterfile", blob);
api.formData('/upload', formData);

// or send with object
api.formData('/upload', {
  username: 'Groucho',
  accountnum: '123456';
  userfile: fileInputElement.files[0],
  webmasterfile: {
    value:  blob,
    options: {
      filename: 'topsecret.jpg',
    }
  }
});

node 端:

var formData = {
  // Pass a simple key-value pair
  my_field: 'my_value',
  // Pass data via Buffers
  my_buffer: new Buffer([1, 2, 3]),
  // Pass data via Streams
  my_file: fs.createReadStream(__dirname + '/unicycle.jpg'),
  // Pass multiple values /w an Array
  attachments: [
    fs.createReadStream(__dirname + '/attachment1.jpg'),
    fs.createReadStream(__dirname + '/attachment2.jpg')
  ],
  custom_file: {
    value:  fs.createReadStream('/dev/urandom'),
    options: {
      filename: 'topsecret.jpg',
      contentType: 'image/jpeg'
    }
  }
};

// send
api.formData('/upload', formData);

相关