13. 使用示例
var request = require('request')
, rand = Math.floor(Math.random()*100000000).toString()
;
request(
{ method: 'PUT'
, uri: 'http://mikeal.iriscouch.com/testjs/' + rand
, multipart:
[ { 'content-type': 'application/json'
, body: JSON.stringify({foo: 'bar', _attachments: {'message.txt': {follows: true, length: 18, 'content_type': 'text/plain' }}})
}
, { body: 'I am an attachment' }
] }
, function (error, response, body) {
if(response.statusCode == 201){
console.log('document saved as: http://mikeal.iriscouch.com/testjs/'+ rand)
} else {
console.log('error: '+ response.statusCode)
console.log(body)
}
}
)为了保持向后兼容,响应压缩默认不会启用。要访问gzip压缩的响应,需要将gzip选项设置为true。这样数据体会通过request自动解压缩,而响应的对象将未包含压缩数据。
var request = require('request')
request(
{ method: 'GET'
, uri: 'http://www.google.com'
, gzip: true
}
, function (error, response, body) {
// body 是解压缩后的 response 响应体
console.log('server encoded the data as: ' + (response.headers['content-encoding'] || 'identity'))
console.log('the decoded data is: ' + body)
}
).on('data', function(data) {
// 收到的是解压缩后的数据
console.log('decoded chunk: ' + data)
})
.on('response', function(response) {
// 未修改 http.IncomingMessage object
response.on('data', function(data) {
// 收到的是压缩数据
console.log('received ' + data.length + ' bytes of compressed data')
})
})Cookie默认是未启用的,可以通过将jar选项设置为true来启用Cookie:
var request = request.defaults({jar: true})
request('http://www.google.com', function () {
request('http://images.google.com')
})使用自定义的Cookie Jar,可以将jar选项设置为一个request.jar()实例:
var j = request.jar()
var request = request.defaults({jar:j})
request('http://www.google.com', function () {
request('http://images.google.com')
})或
var j = request.jar();
var cookie = request.cookie('key1=value1');
var url = 'http://www.google.com';
j.setCookie(cookie, url);
request({url: url, jar: j}, function () {
request('http://images.google.com')
})使用自定义的Cookie存储,可以做为request.jar()的参数传入:
var FileCookieStore = require('tough-cookie-filestore');
// 这时 'cookies.json' 文件必须已经存在









