This article first introduces a node. js module--request. With this module, HTTP requests become super-simple.
Use ultra-simple
Request is super simple and supports both HTTPS and redirection.
var request = require (' request '); Request (' http://www.google.com ', function (error, response, body) {if (!error && ; Response.statuscode = = +) {console.log (body)//print Google home}})
Flow
Any response can be output to a file stream.
Request (' http://google.com/doodle.png '). Pipe (Fs.createwritestream (' doodle.png '))
In turn, you can also pass a file to a put or POST request. If the header is not provided, the file suffix is detected and set accordingly in the PUT request content-type .
Fs.createreadstream (' File.json '). Pipe (Request.put (' Http://mysite.com/obj.json '))
Requests can also be pipe given to themselves. This situation preserves the original content-type and content-length .
Request.get (' http://google.com/img.png '). Pipe (Request.put (' http://mysite.com/img.png '))
Form
requestSupport application/x-www-form-urlencoded and multipart/form-data implement form uploads.
x-www-form-urlencodedVery simple:
Request.post (' Http://service.com/upload ', {form:{key: ' Value '}})
Or:
Request.post (' Http://service.com/upload '). Form ({key: ' Value '})
multipart/form-datathe use of not worrying about setting the header and other trivia, request will help you solve.
var r = request.post (' http://service.com/upload ') var form = R.form () form.append (' My_field ', ' My_value ') form.append (' My_buffer ', New buffer ([1, 2, 3]) form.append (' My_file ', Fs.createreadstream (Path.join (__dirname, ' doodle.png ')) Form.append (' Remote_file ', request (' Http://google.com/doodle.png '))
HTTP Authentication
Request.get (' http://some.server.com/'). Auth (' username ', ' password ', false);
Or
Request.get (' http://some.server.com/', {' auth ': {' user ': ' username ', ' pass ': ' Password ', ' sendimmediately ': false}});
sendImmediately, the default is true, sending a Basic authentication header. When set to false , receive 401 retries (the server's 401 response must contain the WWW-Authenticate specified authentication method).
Sendimmediately supports digest certification when it is true.
OAuth Login
twitter oauthvar qs = require (' querystring ') , oauth = { callback: ' http://mysite.com/callback/' , consumer_key: consumer_key , consumer_ secret: consumer_secret} , url = ' Https://api.twitter.com/oauth/request_token '; Request.post ({url:url, oauth:oauth}, function (e, r, body) { // Ideally, you would take the body in the response // and construct a URL that a user clicks on (like a sign in button) . // the verifier is only available in the Response after a user has // verified with twitter that they are authorizing your app. var access_token = qs.parse (body) oauth = { consUmer_key: consumer_key , consumer_secret: consumer_secret , token: access_ token.oauth_token , verifier: access_token.oauth_verifier} , url = ' https:/ /api.twitter.com/oauth/access_token '; request.post ({url:url, oauth:oauth}, function (E, r, body) { var perm_token = qs.parse (body) , oauth = { consumer_key: consumer_key , consumer_secret: consumer_secret , token: perm_token.oauth_token , token_secret: perm_token.oauth_token_secret} , url = ' Https://api.twitter.com/1/users/show.json? ' , params = { screen_name: perm_token.screen_name , user_id: perm _token.user_id}; url += qs.stringify (params) request.get ({url:url, oauth:oauth, json:true}, function (E, r, user) {console.log (user)})}) Customizing the HTTP Header
User-AgentYou can set it in the options object. In the following example, we call the GitHub API to find out the number of collections and derivations of a warehouse. We have used custom User-Agent and HTTPS.
var request = require (' request '); var options = {url: ' https://api.github.com/repos/mikeal/request ', headers: {' User-age NT ': ' Request '}};function callback (Error, response, body) {if (!error && Response.statuscode = =) {var info = Json.parse (body); Console.log (Info.stargazers_count + "Stars"); Console.log (Info.forks_count + "forks");}} Request (options, callback);
Cookies
By default, cookies are disabled. In defaults or options will be jar set to true enable subsequent requests to use cookies.
var request = Request.defaults ({jar:true}) request (' http://www.google.com ', function () {request (' HTTP/ Images.google.com ')})
By creating request.jar() A new instance, you can use a custom cookie instead of request a global cookie jar.
var j = Request.jar () var request = Request.defaults ({jar:j}) request (' http://www.google.com ', function () {Request (' HTTP ://images.google.com ')})
Or
var j = Request.jar () var cookie = Request.cookie (' Your_cookie_here ') J.setcookie (cookie, URI, function (err, cookie) {}) Request ({URL: ' http://www.google.com ', jar:j}, function () {request (' http://images.google.com ')})
Note that setCookie at least three parameters are required and the last one is a callback function.
Project Home
Request's GitHub homepage
Nodejs Request Usage Introduction