• Stars
    star
    506
  • Rank 87,236 (Top 2 %)
  • Language
    JavaScript
  • Created over 8 years ago
  • Updated almost 3 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Compose HTTP clients using JavaScript's fetch API

http-client Travis npm package

http-client lets you compose HTTP clients using JavaScript's fetch API. This library has the following goals:

  • Preserve the full capabilities of the fetch API
  • Provide an extendable middleware API
  • Use the same API on both client and server

Installation

Using npm:

$ npm install --save http-client

http-client requires you to bring your own global fetch function (for convenience when using the top-level createFetch function). isomorphic-fetch is a great polyfill if you need to support environments that don't already have a global fetch function.

Then, use as you would anything else:

// using ES6 modules
import { createFetch } from 'http-client'

// using CommonJS modules
var createFetch = require('http-client').createFetch

The UMD build is also available on unpkg:

<script src="https://unpkg.com/http-client/umd/http-client.min.js"></script>

You can find the library on window.HTTPClient.

Usage

http-client simplifies the process of creating flexible HTTP clients that work in both node and the browser. You create your own fetch function using the createFetch method, optionally passing middleware as arguments.

import { createFetch, base, accept, parse } from 'http-client'

const fetch = createFetch(
  base('https://api.stripe.com/v1'),  // Prefix all request URLs
  accept('application/json'),         // Set "Accept: application/json" in the request headers
  parse('json')                       // Read the response as JSON and put it in response.body
)

fetch('/customers/5').then(response => {
  console.log(response.jsonData)
})

Top-level API

createFetch(...middleware)

Creates a fetch function that uses some middleware. Uses the global fetch function to actually make the request.

createStack(...middleware)

Combines several middleware into one, in the same order they are provided as arguments. Use this function to create re-usable middleware stacks or if you don't want to use a global fetch function.

enableRecv(fetch)

Returns an "enhanced" version of the given fetch function that knows how to run response handlers registered using recv. This is only really useful when using stacks directly instead of createFetch.

Middleware

http-client provides a variety of middleware that may be used to extend the functionality of the client. Out of the box, http-client ships with the following middleware:

accept(contentType)

Adds an Accept header to the request.

import { createFetch, accept } from 'http-client'

const fetch = createFetch(
  accept('application/json')
)

auth(value)

Adds an Authorization header to the request.

import { createFetch, auth } from 'http-client'

const fetch = createFetch(
  auth('Bearer ' + oauth2Token)
)

base(baseURL)

Adds the given baseURL to the beginning of the request URL.

import { createFetch, base } from 'http-client'

const fetch = createFetch(
  base('https://api.stripe.com/v1')
)

fetch('/customers/5') // GET https://api.stripe.com/v1/customers/5

body(content, contentType)

Sets the given content string as the request body.

import { createFetch, body } from 'http-client'

const fetch = createFetch(
  body(JSON.stringify(data), 'application/json')
)

debug()

Adds a debug property to the response or error object so you can inspect them. Mainly useful for testing/debugging (should run after all other middleware).

import { createFetch, debug } from 'http-client'

const fetch = createFetch(
  // ... other middleware
  debug()
)

fetch(input).then(response => {
  console.log(response.debug.input, response.debug.options)
})

header(name, value)

Adds a header to the request.

import { createFetch, header } from 'http-client'

const fetch = createFetch(
  header('Content-Type', 'application/json')
)

init(propertyName, value)

Sets the value of an arbitrary property in the options object.

import { createFetch, init } from 'http-client'

const fetch = createFetch(
  init('credentials', 'include')
)

json(object)

Adds the data in the given object as JSON to the request body.

method(verb)

Sets the request method.

import { createFetch, method } from 'http-client'

const fetch = createFetch(
  method('POST')
)

params(object)

Adds the given object to the query string of GET/HEAD requests and as a x-www-form-urlencoded payload on all others.

import { createFetch, method, params } from 'http-client'

// Create a client that will append hello=world to the URL in the query string
const fetch = createFetch(
  params({ hello: 'world' })
)

// Create a client that will send hello=world as POST data
const fetch = createFetch(
  method('POST'),
  params({ hello: 'world' })
)

parse(parser, as = 'body')

Reads the response body to completion, parses the response, and puts the result on response.body (or whatever as is). parser must be the name of a valid Body parsing method. The following parsers are available in the spec:

  • arrayBuffer
  • blob
  • formData
  • json
  • text
import { createFetch, parse } from 'http-client'

const fetch = createFetch(
  parse('json')
)

fetch(input).then(response => {
  console.log(response.body)
})

Note: Some parsers may not be available when using a fetch polyfill. In particular if you're using node-fetch, you should be aware of its limitations.

query(object)

Adds the data in the given object (or string) to the query string of the request URL.

recv(handler)

Used to handle the response in some way. The handler function should return the new response value, or a promise for it. Response handlers run in the order they are defined.

import { createFetch, recv } from 'http-client'

const fetch = createFetch(
  recv(response => (console.log('runs first'), response)),
  recv(response => (console.log('runs second'), response))
)

Stacks

Middleware may be combined together into re-usable middleware "stacks" using createStack. A stack is itself a middleware that is composed of one or more other pieces of middleware. Thus, you can pass a stack directly to createFetch as if it were any other piece of middleware.

This is useful when you have a common set of functionality that you'd like to share between several different fetch methods, e.g.:

import { createFetch, createStack, header, base, parse, query } from 'http-client'

const commonStack = createStack(
  header('X-Auth-Key', key),
  header('X-Auth-Email', email),
  base('https://api.cloudflare.com/client/v4'),
  parse('json')
)

// This fetch function can be used standalone...
const fetch = createFetch(commonStack)

// ...or we can add further middleware to create another fetch function!
const fetchSinceBeginningOf2015 = createFetch(
  commonStack,
  query({ since: '2015-01-01T00:00:00Z' })
)

Stacks are also useful when you don't have a global fetch function, e.g. in node. In those cases, you can still use http-client middleware and supply your own fetch (we recommend node-fetch) function directly, but make sure you "enhance" it first:

const { createStack, enableRecv, header, base } = require('http-client')

// We need to "enhance" node-fetch so it knows how to
// handle responses correctly. Specifically, enableRecv
// gives a fetch function the ability to run response
// handlers registered with recv (which parse, used below,
// uses behind the scenes).
const fetch = enableRecv(
  require('node-fetch')
)

const stack = createStack(
  header('X-Auth-Key', key),
  header('X-Auth-Email', email),
  base('https://api.cloudflare.com/client/v4'),
  parse('json')
)

stack(fetch, input, options)

More Repositories

1

unpkg

The CDN for everything on npm
JavaScript
2,989
star
2

expect

Write better assertions
JavaScript
2,291
star
3

mach

HTTP for JavaScript
JavaScript
812
star
4

web-starter

Build and deploy a React website quickly on Heroku
JavaScript
417
star
5

citrus

Parsing Expressions for Ruby
Ruby
403
star
6

strata

A modular, streaming HTTP server for node.js
JavaScript
365
star
7

then-redis

A fast, promise-based Redis client for node.js
JavaScript
315
star
8

shadowbox

A beautiful, versatile lightbox for photos and videos
JavaScript
296
star
9

rollup-plugin-url-resolve

Use URLs in your Rollup imports
JavaScript
136
star
10

react-loop-2019

Notes and code examples from my React Loop 2019 Keynote
JavaScript
116
star
11

resolve-pathname

Resolve URL pathnames using JavaScript
JavaScript
63
star
12

expect-element

Write better assertions for DOM nodes
JavaScript
61
star
13

my-react

An experimental drop-in replacement for React without ES6 classes or "this"
JavaScript
58
star
14

dotfiles

My dotfiles
Vim Script
57
star
15

unpkg-demos

Experiments in how to use unpkg
HTML
54
star
16

history-server

An HTTP server for single-page apps that use the HTML5 history API
JavaScript
52
star
17

rack-accept

HTTP Accept* for Ruby/Rack
Ruby
46
star
18

mint

A small, fast documentation generator for literate-style programming
JavaScript
41
star
19

sinatra-session

Simple, secure sessions for Sinatra
Ruby
38
star
20

firework

A distributed, fault-tolerant work queue for Firebase
JavaScript
38
star
21

s3-thumb-server

Serve thumbnails of images stored on S3 over HTTP
JavaScript
35
star
22

ember-firebase

Firebase bindings for Ember.js
JavaScript
32
star
23

value-equal

Are these two JavaScript values equal?
JavaScript
31
star
24

monterey

Minimal OOP for JavaScript
JavaScript
31
star
25

optionparser

Command-line option parser for PHP
PHP
29
star
26

bufferedstream

A robust stream implementation for node.js and the browser
JavaScript
27
star
27

tree-shaking-react-router

Tree-shaking React Router with webpack 4
JavaScript
25
star
28

icare

A badge to promote empathy in software design, craftsmanship, and maintenance
HTML
25
star
29

react-style

Declarative styling for React components
JavaScript
21
star
30

remix-ssg-example

Small example of how to statically generate a Remix site using wget
TypeScript
19
star
31

dropbox-client

Dropbox API v2 client for JavaScript
JavaScript
17
star
32

bencode

Bencode library for PHP
PHP
15
star
33

reactjsday-2018

Demo + slides from my ReactJS Day 2018 keynote in Verona, Italy
JavaScript
14
star
34

symboltable

A Symbols-only Hash for Ruby
Ruby
13
star
35

broccoli-rev

A Broccoli plugin for adding revision checksums to file names
JavaScript
13
star
36

Fullscreen

A fullscreen sample app for Cocoa with MacRuby
Ruby
12
star
37

yuicompressor

A YUI JavaScript and CSS compressor wrapper for Ruby and JRuby
Ruby
12
star
38

react-router-examples

Code examples for React Router v6
TypeScript
12
star
39

usererror

A base class for JavaScript errors
JavaScript
12
star
40

plural

Pluralization library for PHP
PHP
12
star
41

grand

Generate random data in JavaScript
JavaScript
12
star
42

babel-plugin-import-visitor

Visit all import sources in Babel
JavaScript
10
star
43

then-couchdb

A promise-based CouchDB client for node.js
JavaScript
9
star
44

mwrc2012

Sample code from my talk at MWRC 2012
Ruby
8
star
45

multipart-web-stream

A streaming parser for multipart fetch streams
TypeScript
8
star
46

chatter

A little chat server for #CodeClass
JavaScript
6
star
47

markdown

Markdown as a Service
Ruby
5
star
48

http-client-cookie-jar

Cookie jar middleware for http-client
JavaScript
5
star
49

stratajs.org

The web site for the Strata web framework
JavaScript
5
star
50

form-data-parser

A request.formData() wrapper with pluggable file upload handling
TypeScript
5
star
51

maker

Small library for quickly constructing large segments of HTML in JavaScript
JavaScript
5
star
52

fetch-super-headers

A suite of tools that make it a little more fun to work with Headers
TypeScript
4
star
53

sinatra-spec

Simple specs for Sinatra apps using MiniTest
Ruby
3
star
54

broccoli-select

A Broccoli plugin for selecting files based on glob patterns
JavaScript
3
star
55

jview

A subclass of jQuery.fn for creating views in JavaScript
JavaScript
3
star
56

sequel-factory

Simple, powerful factories for Sequel models
Ruby
3
star
57

describe-property

Define JavaScript object properties quickly with ES5 defaults
JavaScript
3
star
58

mwrc2010

Rack For Web Developers - My presentation from MountainWest RubyConf 2010
Ruby
2
star
59

esbuild-node-builtins-sideeffects

JavaScript
2
star
60

rollup-watch-dir

JavaScript
2
star
61

html5-devconf-may2014

The slides and examples from my presentation at HTML5 DevConf on May 22, 2014
JavaScript
2
star
62

react-router-monorepo-stub

JavaScript
2
star
63

esbuild-empty-file-test

JavaScript
2
star
64

rollup-plugin-babel-bug

JavaScript
2
star
65

rubyconf2010

Grammars, Parsers, and Interpreters. In Ruby. ~ My presentation from RubyConf 2010
Ruby
2
star
66

lazy-file

Lazy, streaming files for JavaScript
TypeScript
2
star
67

jquery-pop

Painless views as models for jQuery
1
star
68

jdrag

Simple drag and drop for jQuery
JavaScript
1
star
69

redemption-from-callback-hell

JavaScript
1
star
70

mjackson.me

JavaScript
1
star
71

file-system

A simple filesystem for JavaScript, based on the File and Streams APIs
TypeScript
1
star
72

JavaScriptObjectsAndPatterns

Some code examples for a class I did for Twitter's HackWeek Q4 2012
JavaScript
1
star
73

mwrc2011

My presentation from MWRC 2011
1
star
74

hoedown2010

My presentation & code for the Ruby Hoedown 2010
1
star