1.0.9 • Published 6 years ago

gent-request v1.0.9

Weekly downloads
4
License
ISC
Repository
github
Last release
6 years ago

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);

相关

1.0.9

6 years ago

1.0.8

6 years ago

1.0.7

6 years ago

1.0.6

6 years ago

1.0.5

6 years ago

1.0.4

6 years ago

1.0.3

6 years ago

1.0.2

6 years ago

1.0.1

6 years ago

1.0.0

6 years ago