Tammy
Note: 基于promise用于浏览器和node.js的http客户端
目录
安装
<script>
标签加载 tammy
使用传统的
使用 CommonJS 方式导入
npm install tammy --save # 浏览器环境 npm install tammy-adapter-xhr --save # nodejs环境 npm install tammy-adapter-request --save # 可选 npm install tammy-plugin-xsrf --save
用法
执行一个 GET
请求
;;httpdefaultsadapter = xhr; // Make a request for a user with a given IDhttp ; // Optionally the request above could also be done ashttp; // 使用 async/await { try const response = await http; console; catch error console; }
NOTE:
async/await
是 ECMAScript 2017 的一部分, 浏览器不一定都支持
执行一个 POST
请求
; request;
执行多个并发请求
; requestall url: '/user/12345' qs: num: 1 '/user/12345/permissions' ;
Tammy API
- Constants
- CT_FORM
- CT_JSON
- CT_FORM_DATA
- CONTENT_TYPES
- ECONNABORTED
- ECONNRESET
- ENETWORK
- EREQCANCELLED
- Request
- cancel
- cancelAll
- create
- http
- Utils
- createError
- forOwn
- formify
- isAbsoluteURL
- isCancelled
- isFunction
- isNil
- isNumber
- isObject
- isString
- joinPath
- joinQuery
- forSlice
- merge
- noop
- remove
- removeAt
- stringifyQuery
- uuid
;
通过相关配置发起请求
http(options)
// Send a POST request ; ;
http(url[, options])
// Send a GET request (default method) ; ;
请求方法别名
http(options)
http.get(url[, data[, options]])
http.delete(url[, data[, options]])
http.del(url[, data[, options]])
http.head(url[, data[, options]])
http.options(url[, data[, options]])
http.post(url[, data[, options]])
http.put(url[, data[, options]])
http.patch(url[, data[, options]])
NOTE: 当使用以上别名方法时,
url
,method
和data
等属性不用在config重复声明。
执行多个并发请求
http.all([ ...options ])
创建一个实例
创建一个拥有通用配置的 tammy
实例
create([options])
;; const instance = ;
实例方法别名
instance(options)
instance.get(url[, data[, options]])
instance.delete(url[, data[, options]])
instance.del(url[, data[, options]])
instance.head(url[, data[, options]])
instance.options(url[, data[, options]])
instance.post(url[, data[, options]])
instance.put(url[, data[, options]])
instance.patch(url[, data[, options]])
配置参数
下面是可用配置项, 只有 url
必填, 如果没有指定方法, 就默认 GET
方法
url
- 请求地址.baseUrl
- 跟路径,将会跟url
拼接.method
- 请求方法 (默认值:"GET"
).headers
- 自定义请求头 (默认值:{'Accept': 'application/json, text/plain, */*'}
).qs
-url
拼接参数, 必须是一个对象或者一个 query string 字符串.data
- 如果是GET
请求, 将转成 query string; 如果是POST
请求, 将根据 content-type 转成 query string 或者 json string.cache
- 如果设置为false
, 将在url
后增加时间戳, 当method
是HEAD
、DELETE
或GET
.timeout
- 请求超时毫秒数 (默认值:0
无超时).adapter
- 自定义适配不同环境 (参考 https://github.com/fengxinming/tammy/blob/dev/packages/tammy-adapter-xhr/src/index.js).
{ /* ... */ }
validateStatus
- 校验 HTTP 响应状态码 (默认值:(status >= 200 && status < 300) || status === 304
.
{ // 校验状态码并返回 bool 值 }
cancelToken
- 保存 token 用于中断请求.
let cancelToken;// ... { cancelToken = token; }
requestType
- 简化设置 content-type, 可选值包括: ‘form’、'json'或'form-data'responseType
- 设置响应数据类型, 可选值包括 'arraybuffer', 'blob', 'document', 'json', 'text', 'stream' (默认值:"json"
).
withCredentials
- 是否携带cookie信息 (默认值:false
).auth
- HTTP Basic auth
auth: username: 'janedoe' password: 's00pers3cret'
xsrfCookieName
xsrf token 名称 (默认值:"XSRF-TOKEN"
).xsrfHeaderName
xsrf token 值 (默认值:"X-XSRF-TOKEN"
).onUploadProgress
- 处理上传进度事件.
{ // Do whatever you want with the native progress event }
onDownloadProgress
- 处理下载进度事件.
{ // Do whatever you want with the native progress event }
Response 结构
Response 包含以下信息.
// `data` 服务端返回的数据 data: {} // `status` 服务端返回的状态码 status: 200 // `statusText` 服务端返回的状态信息 statusText: 'OK' // `headers` 响应头 headers: {} // `config` 请求配置 config: {} // `request` 请求对象 request: {}
使用 then
接受 response 相关信息
; http ;
使用 catch
接受异常信息 rejection callback, 可见 异常处理 区域.
默认参数
全局 http 默认配置
; httpdefaultsbaseUrl = 'https://api.example.com';httpheaderscommonAuthorization = 'authtoken';httpheaderspost'Content-Type' = CT_FORM;
定制 http 实例
; const instance = ;
配置优先级
配置项通过一定的规则合并, request配置将覆盖instance.defaults配置.
; const instance = ; instancedefaultstimeout = 2500; // timeout 将覆盖 instance.defaults.timeoutinstance;
拦截器
增加全局 http 拦截器
// Add a request interceptor; const interceptorId = httpinterceptorsrequest; // Add a response interceptorhttpinterceptorsresponse;
通过 id 或下标移除拦截器
httpinterceptorsrequest;// 或者httpinterceptorsrequest;
增加定制 http 拦截器
; const instance = ;// Add a request interceptorinstanceinterceptorsrequest; // Add a response interceptorinstanceinterceptorsrequest;
异常处理
http ;
校验 HTTP 状态码
http
CancelToken
使用 cancel 方法中断请求
let cancelToken; http; http // cancel the request (the message parameter is optional)http; // cancel all requestshttp;
插件
适配器
License
MIT