request--makes node. JS HTTP requests Super simple

Source: Internet
Author: User
Tags http authentication oauth setcookie

Previous focus on the front-end things, less understanding of the backend. But has been more interested in node. js, last December also attended Ali's Cnode Exchange party.

Later, I want to share some of the notes that I learned from node. js by Blogging here. On the one hand summed up their own learning experience, on the other hand can also share with everyone exchange.

Well, that's probably it.

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 == 200) { console.log(body) // 打印google首页}})
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:consum Er_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 have//verified with Twitter that they be 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:con Sumer_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-Agent‘: ‘request‘}};function callback(error, response, body) { if (!error && response.statusCode == 200) { 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.

request--makes node. JS HTTP requests Super simple

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.