UNPKG

8.28 kBMarkdownView Raw
1# go-fetch
2
3[![Circle CI](https://circleci.com/gh/go-fetch-js/go-fetch.svg?style=svg)](https://circleci.com/gh/go-fetch-js/go-fetch)
4
5A pluggable HTTP client.
6
7## Features
8
9- Support for HTTP and HTTPS
10- Support for streaming
11- Pluggable API with plugins for:
12 - following redirects
13 - compression
14 - parsing JSON
15 - authentication
16 - ... and more
17
18## Usage
19
20### GET
21
22Callback style:
23
24 var Client = require('go-fetch');
25 var body = require('go-fetch-body-parser');
26
27 Client()
28 .use(body())
29 .get('http://httpbin.org/html', function(error, response) {
30
31 console.log(
32 'Error: '+(error ? error : 'no error')+'\n'+
33 'Status: '+response.getStatus()+'\n'+
34 'Headers: '+JSON.stringify(response.getHeaders()).substr(0, 100)+'...'+'\n'+
35 (response.getBody() ? response.getBody().substr(0, 100)+'...' : '')
36 );
37
38 })
39 ;
40
41### POST
42
43Callback style:
44
45 var Client = require('go-fetch');
46 var body = require('go-fetch-body-parser');
47 var contentType = require('go-fetch-content-type');
48
49 Client()
50 .use(contentType)
51 .use(body.json())
52 .post('http://httpbin.org/post', {'Content-Type': 'application/json'}, JSON.stringify({msg: 'Go fetch!'}), function(error, response) {
53
54 console.log(
55 'Error: '+(error ? error : 'no error')+'\n'+
56 'Status: '+response.getStatus()+'\n'+
57 'Headers: '+JSON.stringify(response.getHeaders()).substr(0, 100)+'...'+'\n',
58 response.getBody()
59 );
60
61 })
62 ;
63
64Post a stream:
65
66 var fs = require('fs');
67 var Client = require('go-fetch');
68 var body = require('go-fetch-body-parser');
69
70 Client()
71 .use(body())
72 .post('http://httpbin.org/post', {'Content-Type': 'text/x-markdown'}, fs.createReadStream(__dirname+'/../README.md'), function(error, response) {
73
74 console.log(
75 'Error: '+(error ? error : 'no error')+'\n'+
76 'Status: '+response.getStatus()+'\n'+
77 'Headers: '+JSON.stringify(response.getHeaders()).substr(0, 100)+'...'+'\n',
78 response.getBody()
79 );
80
81 })
82 ;
83
84## API
85
86### Client
87
88A HTTP client.
89
90#### Methods
91
92##### new Client(options) / Client(options)
93
94Create a new client
95
96- https_protocol
97- https_ignore_errors
98
99##### .use(plugin) : Client
100
101Apply a plugin on this client.
102
103Plugins are passed the client object.
104
105##### .get(url, headers) : Request
106
107##### .get(url, headers, callback) : Client
108
109##### .post(url, headers, data) : Request
110
111##### .post(url, headers, data, callback) : Client
112
113##### .put(url, headers, data) : Request
114
115##### .put(url, headers, data, callback) : Client
116
117##### .delete(url, headers, data) : Request
118
119##### .delete(url, headers, data, callback) : Client
120
121##### .send(request) : Response
122
123Send a request.
124
125##### .send(request, callback) : Client
126
127Send a request and handle the response.
128
129##### .on(event, callback) : Client
130
131Add an event listener.
132
133##### .off(event, callback) : Client
134
135Remove an event listener.
136
137#### Events
138
139##### before
140
141Emitted before the request is sent to the server with the following arguments:
142
143- event : Client.Event
144 - .getName() : string
145 - .getEmitter() : Client
146 - .isDefaultPrevented() : bool
147 - .preventDefault()
148 - .isPropagationStopped() : bool
149 - .stopPropagation()
150 - .request : Client.Request
151 - .response : Client.Response
152
153Useful for plugins setting data on the request e.g. OAuth signature
154
155##### after
156
157Emitted after the request is sent to the server with the following arguments:
158
159
160- event : Client.Event
161 - .getName() : string
162 - .getEmitter() : Client
163 - .isPropagationStopped() : bool
164 - .stopPropagation()
165 - .request : Client.Request
166 - .response : Client.Response
167
168
169Useful for plugins processing and setting data on the response e.g. gzip/deflate
170
171##### error
172
173Emitted when an error occurs.
174
175- error : Error
176
177### Request
178
179A HTTP request.
180
181#### Methods
182
183##### new Request(method, url, headers, body)
184
185Create a new request.
186
187##### .setUrl(url) : String
188
189Set the URL.
190
191##### .setHeaders(headers : Object)
192
193Set all the headers.
194
195##### .setHeader(name : string, value : string)
196
197Set a header value.
198
199##### .setBody(data : string|Buffer|Stream)
200
201Set the body data.
202
203### Response
204
205A HTTP response.
206
207#### Methods
208
209##### .getStatus() : number
210
211Get the status code.
212
213##### .getHeaders() : Object
214
215Get all the headers.
216
217##### .getHeader(name : string) : string
218
219Get a header value.
220
221##### .getBody() : string|Buffer|Stream
222
223Get the body data.
224
225##### .abort() : Response
226
227Abort the response.
228
229#### Events
230
231## Plugins
232
233Plugins are functions that are passed the client object to do something with it. Plugins are executed when they are `.use()`d. Using the `before` and `after` events, plugins are able to add helper methods to the `Request` and `Response` objects, modify the request data sent to the server, process the response data received from the server, or cancel the request and use a locally built response.
234
235### Example
236
237Here's an example plugin that adds an `.isError()` method to the `Response` object.
238
239 function plugin(client) {
240 client.on('after', function (event) {
241
242 event.response.isError = function() {
243 return this.getStatus() >= 400 && this.getStatus() < 600;
244 };
245
246 });
247 }
248
249Here's an example plugin that returns a mocked request instead of a real one.
250
251 function(client) {
252 client.on('before', function(event) {
253 event.preventDefault();
254 event.response
255 .setStatus(201)
256 .setHeader('Content-Type', 'application/json; charset=utf-8')
257 .setBody(JSON.stringify({
258 message: 'Hello World!'
259 }))
260 ;
261 });
262 }
263
264### [prefix-url](https://www.npmjs.com/package/go-fetch-prefix-url)
265
266Prefix each request URL with another URL.
267
268### [content-type](https://www.npmjs.com/package/go-fetch-content-type)
269
270Parse the Content-Type header.
271
272### [body-parser](https://www.npmjs.com/package/go-fetch-body-parser)
273
274Concatenate and parse the response stream.
275
276### [auth](https://www.npmjs.com/package/go-fetch-auth)
277
278Basic HTTP auth.
279
280### [oauth1](https://www.npmjs.com/package/go-fetch-oauth1)
281
282OAuth v1 authentication.
283
284### [follow-redirects](https://www.npmjs.com/package/go-fetch-follow-redirects)
285
286Automatically follow redirects.
287
288### [compression](https://www.npmjs.com/package/go-fetch-follow-compression)
289
290Decompress compressed responses from the server.
291
292## ToDo
293
294- Tests
295- Plugins:
296 - Cookie Jar
297 - OAuth v2
298- Support for XMLHttpRequest in the browser
299
300## Changelog
301
302### v2.0.0
303
304 - moved `prefixUrl`, `contentType` and `body` plugins into their own repositories
305 - changed the arguments passed to the `before` and `after` event handlers - handlers now receive a formal event object that allows propagation to be stopped and the request to be prevented
306 - adding some tests
307 - cleaning up documentation
308
309## License
310
311The MIT License (MIT)
312
313Copyright (c) 2014 James Newell
314
315Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
316
317The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
318
319THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
\No newline at end of file