1 | # then-request
|
2 |
|
3 | A request library that returns promises and supports both browsers and node.js
|
4 |
|
5 | [![Build Status](https://img.shields.io/travis/then/then-request/master.svg)](https://travis-ci.org/then/then-request)
|
6 | [![Dependency Status](https://img.shields.io/david/then/then-request.svg)](https://david-dm.org/then/then-request)
|
7 | [![NPM version](https://img.shields.io/npm/v/then-request.svg)](https://www.npmjs.org/package/then-request)
|
8 |
|
9 | <a target='_blank' rel='nofollow' href='https://app.codesponsor.io/link/gg9sZwctSLxyov1sJwW6pfyS/then/then-request'>
|
10 | <img alt='Sponsor' width='888' height='68' src='https://app.codesponsor.io/embed/gg9sZwctSLxyov1sJwW6pfyS/then/then-request.svg' />
|
11 | </a>
|
12 |
|
13 | ## Installation
|
14 |
|
15 | npm install then-request
|
16 |
|
17 | ## Usage
|
18 |
|
19 | `request(method, url, options, callback?)`
|
20 |
|
21 | The following examples all work on both client and server.
|
22 |
|
23 | ```js
|
24 | var request = require('then-request');
|
25 |
|
26 | request('GET', 'http://example.com').done(function (res) {
|
27 | console.log(res.getBody());
|
28 | });
|
29 |
|
30 | request('POST', 'http://example.com/json-api', {json: {some: 'values'}}).getBody('utf8').then(JSON.parse).done(function (res) {
|
31 | console.log(res);
|
32 | });
|
33 |
|
34 | var FormData = request.FormData;
|
35 | var data = new FormData();
|
36 |
|
37 | data.append('some', 'values');
|
38 |
|
39 | request('POST', 'http://example.com/form-api', {form: data}).done(function (res) {
|
40 | console.log(res.getBody());
|
41 | });
|
42 | ```
|
43 |
|
44 | Or with ES6
|
45 |
|
46 | ```js
|
47 | import request, {FormData} from 'then-request';
|
48 |
|
49 | request('GET', 'http://example.com').done((res) => {
|
50 | console.log(res.getBody());
|
51 | });
|
52 |
|
53 | request('POST', 'http://example.com/json-api', {json: {some: 'values'}}).getBody('utf8').then(JSON.parse).done((res) => {
|
54 | console.log(res);
|
55 | });
|
56 |
|
57 | var FormData = request.FormData;
|
58 | var data = new FormData();
|
59 |
|
60 | data.append('some', 'values');
|
61 |
|
62 | request('POST', 'http://example.com/form-api', {form: data}).done((res) => {
|
63 | console.log(res.getBody());
|
64 | });
|
65 | ```
|
66 |
|
67 | **Method:**
|
68 |
|
69 | An HTTP method (e.g. `GET`, `POST`, `PUT`, `DELETE` or `HEAD`). It is not case sensitive.
|
70 |
|
71 | **URL:**
|
72 |
|
73 | A url as a string (e.g. `http://example.com`). Relative URLs are allowed in the browser.
|
74 |
|
75 | **Options:**
|
76 |
|
77 | - `qs` - an object containing querystring values to be appended to the uri
|
78 | - `headers` - http headers (default: `{}`)
|
79 | - `body` - body for PATCH, POST and PUT requests. Must be a `Buffer`, `ReadableStream` or `String` (only strings are accepted client side)
|
80 | - `json` - sets `body` but to JSON representation of value and adds `Content-type: application/json`. Does not have any affect on how the response is treated.
|
81 | - `form` - You can pass a `FormData` instance to the `form` option, this will manage all the appropriate headers for you. Does not have any affect on how the response is treated.
|
82 | - `cache` - only used in node.js (browsers already have their own caches) Can be `'memory'`, `'file'` or your own custom implementaton (see https://github.com/ForbesLindesay/http-basic#implementing-a-cache).
|
83 | - `followRedirects` - defaults to `true` but can be explicitly set to `false` on node.js to prevent then-request following redirects automatically.
|
84 | - `maxRedirects` - sets the maximum number of redirects to follow before erroring on node.js (default: `Infinity`)
|
85 | - `allowRedirectHeaders` (default: `null`) - an array of headers allowed for redirects (none if `null`).
|
86 | - `gzip` - defaults to `true` but can be explicitly set to `false` on node.js to prevent then-request automatically supporting the gzip encoding on responses.
|
87 | - `agent` - (default: `false`) - An `Agent` to controll keep-alive. When set to `false` use an `Agent` with default values.
|
88 | - `timeout` (default: `false`) - times out if no response is returned within the given number of milliseconds.
|
89 | - `socketTimeout` (default: `false`) - calls `req.setTimeout` internally which causes the request to timeout if no new data is seen for the given number of milliseconds. This option is ignored in the browser.
|
90 | - `retry` (default: `false`) - retry GET requests. Set this to `true` to retry when the request errors or returns a status code greater than or equal to 400 (can also be a function that takes `(err, req, attemptNo) => shouldRetry`)
|
91 | - `retryDelay` (default: `200`) - the delay between retries (can also be set to a function that takes `(err, res, attemptNo) => delay`)
|
92 | - `maxRetries` (default: `5`) - the number of times to retry before giving up.
|
93 |
|
94 |
|
95 | **Returns:**
|
96 |
|
97 | A [Promise](https://www.promisejs.org/) is returned that eventually resolves to the `Response`. The resulting Promise also has an additional `.getBody(encoding?)` method that is equivallent to calling `.then(function (res) { return res.getBody(encoding?); })`.
|
98 |
|
99 | ### Response
|
100 |
|
101 | Note that even for status codes that represent an error, the promise will be resolved as the request succeeded. You can call `getBody` if you want to error on invalid status codes. The response has the following properties:
|
102 |
|
103 | - `statusCode` - a number representing the HTTP status code
|
104 | - `headers` - http response headers
|
105 | - `body` - a string if in the browser or a buffer if on the server
|
106 | - `url` - the URL that was requested (in the case of redirects on the server, this is the final url that was requested)
|
107 |
|
108 | It also has a method `getBody(encoding?)` which looks like:
|
109 |
|
110 | ```js
|
111 | function getBody(encoding) {
|
112 | if (this.statusCode >= 300) {
|
113 | var err = new Error('Server responded with status code ' + this.statusCode + ':\n' + this.body.toString(encoding));
|
114 | err.statusCode = this.statusCode;
|
115 | err.headers = this.headers;
|
116 | err.body = this.body;
|
117 | throw err;
|
118 | }
|
119 | return encoding ? this.body.toString(encoding) : this.body;
|
120 | }
|
121 | ```
|
122 |
|
123 | ### FormData
|
124 |
|
125 | ```js
|
126 | var FormData = require('then-request').FormData;
|
127 | ```
|
128 |
|
129 | Form data either exposes the node.js module, [form-data](https://www.npmjs.com/package/form-data), or the builtin browser object [FormData](https://developer.mozilla.org/en/docs/Web/API/FormData), as appropriate.
|
130 |
|
131 | They have broadly the same API, with the exception that form-data handles node.js streams and Buffers, while FormData handles the browser's `File` Objects.
|
132 |
|
133 | ## License
|
134 |
|
135 | MIT
|