微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Fetch HTTP Client 基于 Fetch API 封装的 HTTP Client

程序名称:Fetch HTTP Client

授权协议: MIT

操作系统: 跨平台

开发语言: JavaScript

Fetch HTTP Client 介绍

一个基于 Fetch API 封装的 HTTP
Client,可用于浏览器及其他兼容环境中,设计之初是为了ReactJS和ReactNative访问后端RestAPI使用。比其他基于Fetch
API的封装优势在于,它的中间件机制支持对请求和应答进行异步处理。

安装:

npm install fetch-http-client --save

使用:

import FetchHttpClient, { json } from 'fetch-http-client';

// Create a new client object.
const client = new FetchHttpClient('http://api.example.com/endpoint');

// Add access token
client.addMiddleware(request => {
  request.options.headers['X-Access-Token'] = 'secret';
});

// Add json support
client.addMiddleware(json());

// Add Logging
client.addMiddleware(request => response => {
  console.log(request, response);
});

// Fire request.
client.get('test').then(response => console.log(response.jsonData));

// Path variables support.
client.get('users/{id}', { uriParams: { id: 1 } }).then(response => console.log(response.jsonData));

预处理异步请求的中间件示例,从存储中异步读取accesstoken,并添加到请求头中:

// Add access token asynchronously
client.addMiddleware(request => {
  return Asynchronousstorage.fetch('accesstoken').then(token => {
    request.options.headers['X-Access-Token'] = token;
    return request;
  });
});

Fetch HTTP Client 官网

https://github.com/starlight36/fetch-http-client

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐