一个基于FetchAPI封装的HTTPClient,可用于浏览器及其他兼容环境中,设计之初是为了ReactJS和ReactNative访问后端RestAPI使用。比其他基于FetchAPI的封装优势在于,它的中间件机制支持对请求和应答进行异步处理。
安装:
npm install fetch-http-client --save使用:
import FetchHttpClient, { json } from 'fetch-http-client';// Create a new client object.const client = new FetchHttpClient('https://api.example.com/endpoint');// Add access tokenclient.addMiddleware(request => { request.options.headers['X-Access-Token'] = 'secret';});// Add json supportclient.addMiddleware(json());// Add Loggingclient.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 asynchronouslyclient.addMiddleware(request => { return AsynchronousStorage.fetch('accessToken').then(token => { request.options.headers['X-Access-Token'] = token; return request; });});
评论