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' 文件必须已经存在 var j = request.jar(new FileCookieStore('cookies.json')); request = request.defaults({ jar : j }) request('http://www.google.com', function() { request('http://images.google.com') }
Cookie存储必须是一个tough-cookie且必须支持同步操作。
在请求完成后,检查你的Cookie Jar:
var j = request.jar() request({url: 'http://www.google.com', jar: j}, function () { var cookie_string = j.getCookieString(url); // "key1=value1; key2=value2; ..." var cookies = j.getCookies(url); // [{key: 'key1', value: 'value1', domain: "www.google.com", ...}, ...] })