1 | # sync-request
|
2 |
|
3 | Make synchronous web requests with cross-platform support.
|
4 |
|
5 | > Requires at least node 8
|
6 |
|
7 | # **N.B.** You should **not** be using this in a production application. In a node.js application you will find that you are completely unable to scale your server. In a client application you will find that sync-request causes the app to hang/freeze. Synchronous web requests are the number one cause of browser crashes. For production apps, you should use [then-request](https://github.com/then/then-request), which is exactly the same except that it is asynchronous.
|
8 |
|
9 | [![Build Status](https://img.shields.io/travis/ForbesLindesay/sync-request/master.svg)](https://travis-ci.org/ForbesLindesay/sync-request)
|
10 | [![Dependency Status](https://img.shields.io/david/ForbesLindesay/sync-request.svg)](https://david-dm.org/ForbesLindesay/sync-request)
|
11 | [![NPM version](https://img.shields.io/npm/v/sync-request.svg)](https://www.npmjs.org/package/sync-request)
|
12 |
|
13 | ## Installation
|
14 |
|
15 | npm install sync-request
|
16 |
|
17 | ## Usage
|
18 |
|
19 | ```js
|
20 | request(method, url, options);
|
21 | ```
|
22 |
|
23 | e.g.
|
24 |
|
25 | * GET request without options
|
26 |
|
27 | ```js
|
28 | var request = require('sync-request');
|
29 | var res = request('GET', 'http://example.com');
|
30 | console.log(res.getBody());
|
31 | ```
|
32 |
|
33 | * GET request with options
|
34 |
|
35 | ```js
|
36 | var request = require('sync-request');
|
37 | var res = request('GET', 'https://example.com', {
|
38 | headers: {
|
39 | 'user-agent': 'example-user-agent',
|
40 | },
|
41 | });
|
42 | console.log(res.getBody());
|
43 | ```
|
44 |
|
45 | * POST request to a JSON endpoint
|
46 |
|
47 | ```js
|
48 | var request = require('sync-request');
|
49 | var res = request('POST', 'https://example.com/create-user', {
|
50 | json: {username: 'ForbesLindesay'},
|
51 | });
|
52 | var user = JSON.parse(res.getBody('utf8'));
|
53 | ```
|
54 |
|
55 | **Method:**
|
56 |
|
57 | An HTTP method (e.g. `GET`, `POST`, `PUT`, `DELETE` or `HEAD`). It is not case sensitive.
|
58 |
|
59 | **URL:**
|
60 |
|
61 | A url as a string (e.g. `http://example.com`). Relative URLs are allowed in the browser.
|
62 |
|
63 | **Options:**
|
64 |
|
65 | * `qs` - an object containing querystring values to be appended to the uri
|
66 | * `headers` - http headers (default: `{}`)
|
67 | * `body` - body for PATCH, POST and PUT requests. Must be a `Buffer` or `String` (only strings are accepted client side)
|
68 | * `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.
|
69 | * `cache` - Set this to `'file'` to enable a local cache of content. A separate process is still spawned even for cache requests. This option is only used if running in node.js
|
70 | * `followRedirects` - defaults to `true` but can be explicitly set to `false` on node.js to prevent then-request following redirects automatically.
|
71 | * `maxRedirects` - sets the maximum number of redirects to follow before erroring on node.js (default: `Infinity`)
|
72 | * `allowRedirectHeaders` (default: `null`) - an array of headers allowed for redirects (none if `null`).
|
73 | * `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.
|
74 | * `timeout` (default: `false`) - times out if no response is returned within the given number of milliseconds.
|
75 | * `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.
|
76 | * `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
|
77 | * `retryDelay` (default: `200`) - the delay between retries in milliseconds
|
78 | * `maxRetries` (default: `5`) - the number of times to retry before giving up.
|
79 |
|
80 | These options are passed through to [then-request](https://github.com/then/then-request), so any options that work for then-request should work for sync-request (with the exception of custom and memory caching strategies, and passing functions for handling retries).
|
81 |
|
82 | **Returns:**
|
83 |
|
84 | A `Response` object.
|
85 |
|
86 | Note that even for status codes that represent an error, the request function will still return a response. You can call `getBody` if you want to error on invalid status codes. The response has the following properties:
|
87 |
|
88 | * `statusCode` - a number representing the HTTP status code
|
89 | * `headers` - http response headers
|
90 | * `body` - a string if in the browser or a buffer if on the server
|
91 |
|
92 | It also has a method `res.getBody(encoding?)` which looks like:
|
93 |
|
94 | ```js
|
95 | function getBody(encoding) {
|
96 | if (this.statusCode >= 300) {
|
97 | var err = new Error(
|
98 | 'Server responded with status code ' +
|
99 | this.statusCode +
|
100 | ':\n' +
|
101 | this.body.toString(encoding)
|
102 | );
|
103 | err.statusCode = this.statusCode;
|
104 | err.headers = this.headers;
|
105 | err.body = this.body;
|
106 | throw err;
|
107 | }
|
108 | return encoding ? this.body.toString(encoding) : this.body;
|
109 | }
|
110 | ```
|
111 |
|
112 | ## Common Problems
|
113 |
|
114 | ### Could not use "nc", falling back to slower node.js method for sync requests.
|
115 |
|
116 | If you are running on windows, or some unix systems, you may see the message above. It will not cause any problems, but will add an overhead of ~100ms to each request you make. If you want to speed up your requests, you will need to install an implementation of the `nc` unix utility. This usually done via something like:
|
117 |
|
118 | ```
|
119 | apt-get install netcat
|
120 | ```
|
121 |
|
122 | ## How is this possible?
|
123 |
|
124 | Internally, this uses a separate worker process that is run using [childProcess.spawnSync](http://nodejs.org/docs/v0.11.13/api/child_process.html#child_process_child_process_spawnsync_command_args_options).
|
125 |
|
126 | The worker then makes the actual request using [then-request](https://www.npmjs.org/package/then-request) so this has almost exactly the same API as that.
|
127 |
|
128 | This can also be used in a web browser via browserify because xhr has built in support for synchronous execution. Note that this is not recommended as it will be blocking.
|
129 |
|
130 | ## License
|
131 |
|
132 | MIT
|