Previously, we paid more attention to the front-end, but less attention to the back-end. However, I have always been interested in Node.js, and I went to CNODE exchange party in Ali last December.
I hope to share some notes about learning Node.js through my blog here in the future. On the one hand, I summarized my learning experience, on the other hand, I can share with you.
Well, that's probably what it is.
This article begins with a Node.js module called request. With this module, http requests become extremely simple.
Ultra simple to use
Request is extremely simple to use, while supporting https and redirection.
var request = require('request');
request('http://www.google.com', function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body) // Print google Home Page
}
})
flow
Any response can be output to the file stream.
request('http://google.com/doodle.png').pipe(fs.createWriteStream('doodle.png'))
Conversely, files can also be passed to PUT or POST requests. If header is not provided, the suffix name of the file is detected and the corresponding content-type is set in the PUT request.
fs.createReadStream('file.json').pipe(request.put('http://mysite.com/obj.json'))
Requests can also be pipe d to yourself. In this case, the original content-type and content-length will be retained.
request.get('http://google.com/img.png').pipe(request.put('http://mysite.com/img.png'))
form
request supports application/x-www-form-urlencoded and multipart/form-data for form upload.
x-www-form-urlencoded is simple:
request.post('http://service.com/upload', {form:{key:'value'}})
Or:
request.post('http://service.com/upload').form({key:'value'})
Using multipart/form-data, you don't have to worry about setting up header s or other trivial things, request s will help you solve them.
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
}
});
Send Immediately, which defaults to true, sends a basic authentication header. When set to false, the server receives 401 and retries (the server 401 response must contain the WWW-Authenticate specified authentication method).
sendImmediately supports Digest authentication when it is true.
OAuth login
// Twitter OAuth
var 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)
})
})
})
Customize HTTP header
User-Agent and others can be set in options objects. In the following example, we call the github API to find out the number of collections and derivatives of a warehouse. We 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. Set jar to true in defaults or options so that cookies are used for subsequent requests.
var request = request.defaults({jar: true})
request('http://www.google.com', function () {
request('http://images.google.com')
})
By creating a new instance of request.jar(), you can use a custom cookie instead of a request global cookie jar.
var j = request.jar()
var request = request.defaults({jar:j})
request('http://www.google.com', function () {
request('http://images.google.com')
})
perhaps
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 requires at least three parameters, and the last one is the callback function.