Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

12 лет назад
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288
  1. # Request -- Simplified HTTP request method
  2. ## Install
  3. <pre>
  4. npm install request
  5. </pre>
  6. Or from source:
  7. <pre>
  8. git clone git://github.com/mikeal/request.git
  9. cd request
  10. npm link
  11. </pre>
  12. ## Super simple to use
  13. Request is designed to be the simplest way possible to make http calls. It support HTTPS and follows redirects by default.
  14. ```javascript
  15. var request = require('request');
  16. request('http://www.google.com', function (error, response, body) {
  17. if (!error && response.statusCode == 200) {
  18. console.log(body) // Print the google web page.
  19. }
  20. })
  21. ```
  22. ## Streaming
  23. You can stream any response to a file stream.
  24. ```javascript
  25. request('http://google.com/doodle.png').pipe(fs.createWriteStream('doodle.png'))
  26. ```
  27. You can also stream a file to a PUT or POST request. This method will also check the file extension against a mapping of file extensions to content-types, in this case `application/json`, and use the proper content-type in the PUT request if one is not already provided in the headers.
  28. ```javascript
  29. fs.createReadStream('file.json').pipe(request.put('http://mysite.com/obj.json'))
  30. ```
  31. Request can also pipe to itself. When doing so the content-type and content-length will be preserved in the PUT headers.
  32. ```javascript
  33. request.get('http://google.com/img.png').pipe(request.put('http://mysite.com/img.png'))
  34. ```
  35. Now let's get fancy.
  36. ```javascript
  37. http.createServer(function (req, resp) {
  38. if (req.url === '/doodle.png') {
  39. if (req.method === 'PUT') {
  40. req.pipe(request.put('http://mysite.com/doodle.png'))
  41. } else if (req.method === 'GET' || req.method === 'HEAD') {
  42. request.get('http://mysite.com/doodle.png').pipe(resp)
  43. }
  44. }
  45. })
  46. ```
  47. You can also pipe() from a http.ServerRequest instance and to a http.ServerResponse instance. The HTTP method and headers will be sent as well as the entity-body data. Which means that, if you don't really care about security, you can do:
  48. ```javascript
  49. http.createServer(function (req, resp) {
  50. if (req.url === '/doodle.png') {
  51. var x = request('http://mysite.com/doodle.png')
  52. req.pipe(x)
  53. x.pipe(resp)
  54. }
  55. })
  56. ```
  57. And since pipe() returns the destination stream in node 0.5.x you can do one line proxying :)
  58. ```javascript
  59. req.pipe(request('http://mysite.com/doodle.png')).pipe(resp)
  60. ```
  61. Also, none of this new functionality conflicts with requests previous features, it just expands them.
  62. ```javascript
  63. var r = request.defaults({'proxy':'http://localproxy.com'})
  64. http.createServer(function (req, resp) {
  65. if (req.url === '/doodle.png') {
  66. r.get('http://google.com/doodle.png').pipe(resp)
  67. }
  68. })
  69. ```
  70. You can still use intermediate proxies, the requests will still follow HTTP forwards, etc.
  71. ## OAuth Signing
  72. ```javascript
  73. // Twitter OAuth
  74. var qs = require('querystring')
  75. , oauth =
  76. { callback: 'http://mysite.com/callback/'
  77. , consumer_key: CONSUMER_KEY
  78. , consumer_secret: CONSUMER_SECRET
  79. }
  80. , url = 'https://api.twitter.com/oauth/request_token'
  81. ;
  82. request.post({url:url, oauth:oauth}, function (e, r, body) {
  83. // Assume by some stretch of magic you aquired the verifier
  84. var access_token = qs.parse(body)
  85. , oauth =
  86. { consumer_key: CONSUMER_KEY
  87. , consumer_secret: CONSUMER_SECRET
  88. , token: access_token.oauth_token
  89. , verifier: VERIFIER
  90. , token_secret: access_token.oauth_token_secret
  91. }
  92. , url = 'https://api.twitter.com/oauth/access_token'
  93. ;
  94. request.post({url:url, oauth:oauth}, function (e, r, body) {
  95. var perm_token = qs.parse(body)
  96. , oauth =
  97. { consumer_key: CONSUMER_KEY
  98. , consumer_secret: CONSUMER_SECRET
  99. , token: perm_token.oauth_token
  100. , token_secret: perm_token.oauth_token_secret
  101. }
  102. , url = 'https://api.twitter.com/1/users/show.json?'
  103. , params =
  104. { screen_name: perm_token.screen_name
  105. , user_id: perm_token.user_id
  106. }
  107. ;
  108. url += qs.stringify(params)
  109. request.get({url:url, oauth:oauth, json:true}, function (e, r, user) {
  110. console.log(user)
  111. })
  112. })
  113. })
  114. ```
  115. ### request(options, callback)
  116. The first argument can be either a url or an options object. The only required option is uri, all others are optional.
  117. * `uri` || `url` - fully qualified uri or a parsed url object from url.parse()
  118. * `qs` - object containing querystring values to be appended to the uri
  119. * `method` - http method, defaults to GET
  120. * `headers` - http headers, defaults to {}
  121. * `body` - entity body for POST and PUT requests. Must be buffer or string.
  122. * `form` - sets `body` but to querystring representation of value and adds `Content-type: application/x-www-form-urlencoded; charset=utf-8` header.
  123. * `json` - sets `body` but to JSON representation of value and adds `Content-type: application/json` header.
  124. * `multipart` - (experimental) array of objects which contains their own headers and `body` attribute. Sends `multipart/related` request. See example below.
  125. * `followRedirect` - follow HTTP 3xx responses as redirects. defaults to true.
  126. * `followAllRedirects` - follow non-GET HTTP 3xx responses as redirects. defaults to false.
  127. * `maxRedirects` - the maximum number of redirects to follow, defaults to 10.
  128. * `onResponse` - If true the callback will be fired on the "response" event instead of "end". If a function it will be called on "response" and not effect the regular semantics of the main callback on "end".
  129. * `encoding` - Encoding to be used on `setEncoding` of response data. If set to `null`, the body is returned as a Buffer.
  130. * `pool` - A hash object containing the agents for these requests. If omitted this request will use the global pool which is set to node's default maxSockets.
  131. * `pool.maxSockets` - Integer containing the maximum amount of sockets in the pool.
  132. * `timeout` - Integer containing the number of milliseconds to wait for a request to respond before aborting the request
  133. * `proxy` - An HTTP proxy to be used. Support proxy Auth with Basic Auth the same way it's supported with the `url` parameter by embedding the auth info in the uri.
  134. * `oauth` - Options for OAuth HMAC-SHA1 signing, see documentation above.
  135. * `strictSSL` - Set to `true` to require that SSL certificates be valid. Note: to use your own certificate authority, you need to specify an agent that was created with that ca as an option.
  136. * `jar` - Set to `false` if you don't want cookies to be remembered for future use or define your custom cookie jar (see examples section)
  137. The callback argument gets 3 arguments. The first is an error when applicable (usually from the http.Client option not the http.ClientRequest object). The second in an http.ClientResponse object. The third is the response body String or Buffer.
  138. ## Convenience methods
  139. There are also shorthand methods for different HTTP METHODs and some other conveniences.
  140. ### request.defaults(options)
  141. This method returns a wrapper around the normal request API that defaults to whatever options you pass in to it.
  142. ### request.put
  143. Same as request() but defaults to `method: "PUT"`.
  144. ```javascript
  145. request.put(url)
  146. ```
  147. ### request.post
  148. Same as request() but defaults to `method: "POST"`.
  149. ```javascript
  150. request.post(url)
  151. ```
  152. ### request.head
  153. Same as request() but defaults to `method: "HEAD"`.
  154. ```javascript
  155. request.head(url)
  156. ```
  157. ### request.del
  158. Same as request() but defaults to `method: "DELETE"`.
  159. ```javascript
  160. request.del(url)
  161. ```
  162. ### request.get
  163. Alias to normal request method for uniformity.
  164. ```javascript
  165. request.get(url)
  166. ```
  167. ### request.cookie
  168. Function that creates a new cookie.
  169. ```javascript
  170. request.cookie('cookie_string_here')
  171. ```
  172. ### request.jar
  173. Function that creates a new cookie jar.
  174. ```javascript
  175. request.jar()
  176. ```
  177. ## Examples:
  178. ```javascript
  179. var request = require('request')
  180. , rand = Math.floor(Math.random()*100000000).toString()
  181. ;
  182. request(
  183. { method: 'PUT'
  184. , uri: 'http://mikeal.iriscouch.com/testjs/' + rand
  185. , multipart:
  186. [ { 'content-type': 'application/json'
  187. , body: JSON.stringify({foo: 'bar', _attachments: {'message.txt': {follows: true, length: 18, 'content_type': 'text/plain' }}})
  188. }
  189. , { body: 'I am an attachment' }
  190. ]
  191. }
  192. , function (error, response, body) {
  193. if(response.statusCode == 201){
  194. console.log('document saved as: http://mikeal.iriscouch.com/testjs/'+ rand)
  195. } else {
  196. console.log('error: '+ response.statusCode)
  197. console.log(body)
  198. }
  199. }
  200. )
  201. ```
  202. Cookies are enabled by default (so they can be used in subsequent requests). To disable cookies set jar to false (either in defaults or in the options sent).
  203. ```javascript
  204. var request = request.defaults({jar: false})
  205. request('http://www.google.com', function () {
  206. request('http://images.google.com')
  207. })
  208. ```
  209. If you to use a custom cookie jar (instead of letting request use its own global cookie jar) you do so by setting the jar default or by specifying it as an option:
  210. ```javascript
  211. var j = request.jar()
  212. var request = request.defaults({jar:j})
  213. request('http://www.google.com', function () {
  214. request('http://images.google.com')
  215. })
  216. ```
  217. OR
  218. ```javascript
  219. var j = request.jar()
  220. var cookie = request.cookie('your_cookie_here')
  221. j.add(cookie)
  222. request({url: 'http://www.google.com', jar: j}, function () {
  223. request('http://images.google.com')
  224. })
  225. ```