Request 是一个 Node.jsNPM 模块, 它是一个 HTTP 客户端, 使用简单功能确十分强大. 我们可以用它来实现 HTTP 响应流的转接, 模拟 Form 表单提交, 支持 HTTP 认证, OAuth 登录, 自定义请求头等. 下面我们来对这个模块做一个完整的介绍:
1. 安装及简单使用
安装 request 模块:
npm install request
Request 设计为用最简单的方法发送 HTTP 请求, 它还支持 HTTPS 请求和自动重定向跟踪:
- var request = require('request');
- request('http://www.baidu.com', function (error, response, body) {
- if (!error && response.statusCode == 200) {
- console.log(body) // IT 笔录主页的 HTML
- }
- })
引用 request 模块后, 就可以能通过 request()方法来发送 HTTP 请求, 在不指定请求选项 option 时, 默认为 GET. 在上面请求中, 对 URLhttp://www.baidu.com
会 301 重定向到 http://www.baidu.com. 而 Request 会自动跟踪 URL 重定向请求, 默认支持 10 次重定向跟踪.
2. 流 (stream) 操作
Node.js 原生 HTTP 模块实现了对 HTTP 请求和响应对象的流操作, Request 同样支持基于流的操作.
如, 可以将任何响应流通过 pipe 转接到一个文件流:
复制代码 代码如下:
request('http://google.com/doodle.png').pipe(fs.createWriteStream('doodle.png'))
同样, 可以将一个读取的文件流转接到 PUT 或 POST 请求中. 这个方法会自动检查文件扩展名, 并设置一个与文件扩展名对应的 content-type(当该请求头未设置时):
复制代码 代码如下:
fs.createReadStream('file.json').pipe(request.put('http://mysite.com/obj.json'))
Request 也支持 pipe 到它自己. 这样操作时, content-type 和 content-length 将被传递到其后的 PUT 请求中:
复制代码 代码如下:
request.get('http://google.com/img.png').pipe(request.put('http://mysite.com/img.png'))
与原生 HTTP 客户端一样, Request 在收到请求响应时会发送一个'response'. 事件回调函数中会包含一个 response 参数, 它是一个 http.IncomingMessage 实例:
- request
- .get('http://google.com/img.png')
- .on('response', function(response) {
- console.log(response.statusCode) // 200
- console.log(response.headers['content-type']) // 'image/png'
- })
- .pipe(request.put('http://mysite.com/img.png'))
当请求发生错误时, 可以简单的通过监听 error 事件来处理:
- request
- .get('http://mysite.com/doodle.png')
- .on('error', function(err) {
- console.log(err)
- })
- .pipe(fs.createWriteStream('doodle.png'))
发挥一个想象:
- http.createServer(function (req, resp) {
- if (req.url === '/doodle.png') {
- if (req.method === 'PUT') {
- req.pipe(request.put('http://mysite.com/doodle.png'))
- } else if (req.method === 'GET' || req.method === 'HEAD') {
- request.get('http://mysite.com/doodle.png').pipe(resp)
- }
- }
- })
也可以使用 pipe()方法将一个 http.ServerRequest 实例转换到一个 http.ServerResponse.HTTP 请求方法, 请求头, 请求体数据会被发送:
- http.createServer(function (req, resp) {
- if (req.url === '/doodle.png') {
- var x = request('http://mysite.com/doodle.png')
- req.pipe(x)
- x.pipe(resp)
- }
- })
通过 pipe()返回的目标流, 在 Nodev0.5.x + 版本中, 可以写到一行:
复制代码 代码如下:
req.pipe(request('http://mysite.com/doodle.png')).pipe(resp)
而所有这些, 没有一个新功能会与原功能有冲突, 只是对其进行了扩展. 还可以使用 HTTP 代理, 请求会被自动重定向并跟踪:
- var r = request.defaults({'proxy':'http://localproxy.com'})
- http.createServer(function (req, resp) {
- if (req.url === '/doodle.png') {
- r.get('http://google.com/doodle.png').pipe(resp)
- }
- })
3. Form 表单
request 支付 application/x-www-form-urlencoded 和 multipart/form-data 编码的 form 上传. multipart/related 会引用 multipartAPI.
application/x-www-form-urlencoded (URL 编码的 Form)
URL 编码的 Form 很简单:
- request.post('http://service.com/upload', {form:{key:'value'}})
- // or
- request.post('http://service.com/upload').form({key:'value'})
- // or
- request.post({url:'http://service.com/upload', form: {key:'value'}}, function(err,httpResponse,body){ /* ... */ })
- multipart/form-data (Multipart Form 上传)
对于 multipart/form-dataFrom 文件上传, Request 使用了 form-data 处理. 大多数情况, 可以通过 formData 选项添加上传文件:
- var formData = {
- // 键 - 值对简单值
- my_field: 'my_value',
- // 使用 Buffers 添加数据
- my_buffer: new Buffer([1, 2, 3]),
- // 使用 Streams 添加数据
- my_file: fs.createReadStream(__dirname + '/unicycle.jpg'),
- // 通过数组添加 multiple 值
- attachments: [fs.createReadStream(__dirname + '/attachment1.jpg'), fs.createReadStream(__dirname + '/attachment2.jpg')],
- // 添加可选的 meta-data 使用: {value: DATA, options: OPTIONS}
- // 对于一些流类型, 需要提供手工添加 "file"- 关联
- // 详细查看 `form-data` : https://github.com/form-data/form-data
- custom_file: {
- value: fs.createReadStream('/dev/urandom'),
- options: {
- filename: 'topsecret.jpg',
- contentType: 'image/jpg'
- }
- }
- };
- request.post({
- url: 'http://service.com/upload',
- formData: formData
- },
- function optionalCallback(err, httpResponse, body) {
- if (err) {
- return console.error('upload failed:', err);
- }
- console.log('Upload successful! Server responded with:', body);
- });
在一些更加高级的使用中, 可以通过其自身的如 r.form()来访问 Form 数据:
- // NOTE: Advanced use-case, for normal use see 'formData' usage above
- var r = request.post('http://service.com/upload', function optionalCallback(err, httpResponse, body) {...})
- var form = r.form();
- form.append('my_field', 'my_value');
- form.append('my_buffer', new Buffer([1, 2, 3]));
- form.append('custom_file', fs.createReadStream(__dirname + '/unicycle.jpg'), {filename: 'unicycle.jpg'});
multipart/related
在一些不同的 HTTP 实现中, 需要在 multipart/related 的之前, 之后或前后同时添加一个 newline/CRLF(通过 multipart 选项). 特别是在. NET WebAPI 4.0 中, 需要将 preambleCRLF 设置为 true:
- request({
- method: 'PUT',
- preambleCRLF: true,
- postambleCRLF: true,
- uri: 'http://service.com/upload',
- 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' },
- { body: fs.createReadStream('image.png') }
- ],
- // alternatively pass an object containing additional options
- multipart: {
- chunked: false,
- data: [
- {
- '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 (error) {
- return console.error('upload failed:', error);
- }
- console.log('Upload successful! Server responded with:', body);
- })
4. HTTP 认证
在一些 HTTP 请求中, 需要对请求对象进行身份验证. Request 提供了多种身份验证方式:
- request.get('http://some.server.com/').auth('username', 'password', false);
- // or
- request.get('http://some.server.com/', {
- 'auth': {
- 'user': 'username',
- 'pass': 'password',
- 'sendImmediately': false
- }
- });
- // or
- request.get('http://some.server.com/').auth(null, null, true, 'bearerToken');
- // or
- request.get('http://some.server.com/', {
- 'auth': {
- 'bearer': 'bearerToken'
- }
- });
当使用 auth 选项进, 其可包含以下值:
- user || username
- pass || password
- sendImmediately (可选)
- bearer (可选)
而对于最终调用的 auth(username, password, sendImmediately, bearer)方法来说, sendImmediately 默认为 true, 这会导致一个 basic 或 bearer 认证头会被发送. 如果 sendImmediately 设置为 false,request 会在收到 401 状态后尝试使用一个合适的认证头.
注意, 也可以基于 RFC 1738 标准, 在 URL 中添加认证信息. 简单的是使用方式是在主机的 @符号前添加 user:password:
- var username = 'username',
- password = 'password',
- url = 'http://' + username + ':' + password + '@some.server.com';
- request({url: url}, function (error, response, body) {
- // Do more stuff with 'body' here
- });
5. 自定义 HTTP 头
如果需要设置自定义的 HTTP 请求头, 如: User-Agent, 可以通过 options 对象设置.
- var request = require('request');
- var options = {
- url: 'https://api.github.com/repos/request/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);
6. OAuth 签名
Request 支持 OAuth 1.0. 其默认使用的签名算法为 HMAC-SHA1:
- // OAuth1.0 - 3-legged server side flow (Twitter example)
- // step 1
- 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.
- // step 2
- var req_data = qs.parse(body)
- var uri = 'https://api.twitter.com/oauth/authenticate'
- + '?' + qs.stringify({oauth_token: req_data.oauth_token})
- // redirect the user to the authorize uri
- // step 3
- // after the user is redirected back to your server
- var auth_data = qs.parse(body)
- , oauth =
- { consumer_key: CONSUMER_KEY
- , consumer_secret: CONSUMER_SECRET
- , token: auth_data.oauth_token
- , token_secret: req_data.oauth_token_secret
- , verifier: auth_data.oauth_verifier
- }
- , url = 'https://api.twitter.com/oauth/access_token'
- ;
- request.post({url:url, oauth:oauth}, function (e, r, body) {
- // ready to make signed requests on behalf of the user
- var perm_data = qs.parse(body)
- , oauth =
- { consumer_key: CONSUMER_KEY
- , consumer_secret: CONSUMER_SECRET
- , token: perm_data.oauth_token
- , token_secret: perm_data.oauth_token_secret
- }
- , url = 'https://api.twitter.com/1.1/users/show.json'
- , qs =
- { screen_name: perm_data.screen_name
- , user_id: perm_data.user_id
- }
- ;
- request.get({url:url, oauth:oauth, qs:qs, json:true}, function (e, r, user) {
- console.log(user)
- })
- })
- })
使用 RSA-SHA1 签名时, 可传入如下一个 OAuth 对象:
指定 signature_method : 'RSA-SHA1'
代替 consumer_secret, 指定 private_key 字符串为 PEM format
而使用 PLAINTEXT 签名, 可传入如下一个 OAuth 对象:
指定 signature_method : 'PLAINTEXT'
7. 代理
如果指定 proxy(代理)选项后, 所有的请求 (及其后的重定向) 都会连接到该代理服务器.
如果终端是一个 httpsURL, 代理会使用 CONNECT 请求连接到代理服务器.
首先会生成类似如下一个请求:
- HTTP/1.1 CONNECT endpoint-server.com:80
- Host: proxy-server.com
- User-Agent: whatever user agent you specify
然后建立一个到 endpoint-server(终端服务器)的 80 端口的 TCP 连接, 并按如下返回响应:
HTTP/1.1 200 OK
默认情况下, 当代理使用 http 进行通讯时, request 会简单的生成一个标准的 http 代理请求. 如, 会像如下这样生成一个请求:
- HTTP/1.1 GET http://endpoint-server.com/some-url
- Host: proxy-server.com
- Other-Headers: all go here
request body or whatever
通过 proxyHeaderExclusiveList 选项可以明确指定一些代理头, 默认会按如下方式设置:
- accept
- accept-charset
- accept-encoding
- accept-language
- accept-ranges
- cache-control
- content-encoding
- content-language
- content-length
- content-location
- content-md5
- content-range
- content-type
- connection
- date
- expect
- max-forwards
- pragma
- proxy-authorization
- referer
- te
- transfer-encoding
- user-agent
- via
8. UNIX 域套接字
request 支持到 UNIX 域套接字的请求:
- /* Pattern */ 'http://unix:SOCKET:PATH'
- /* Example */ request.get('http://unix:/absolute/path/to/unix.socket:/request/path')
注意: SOCKET 应该是一个到文件系统根目录的绝对路径.
9. TLS/SSL 协议
对于使用了 TLS/SSL 等安全协议的请求, 可以使用相关选项如 cert,key,passphrase 也可以使用 agentOptions 选项甚至使用 https.globalAgent.options 来设置:
- var fs = require('fs')
- , path = require('path')
- , certFile = path.resolve(__dirname, 'ssl/client.crt')
- , keyFile = path.resolve(__dirname, 'ssl/client.key')
- , caFile = path.resolve(__dirname, 'ssl/ca.cert.pem')
- , request = require('request');
- var options = {
- url: 'https://api.some-server.com/',
- cert: fs.readFileSync(certFile),
- key: fs.readFileSync(keyFile),
- passphrase: 'password',
- ca: fs.readFileSync(caFile)
- }
- };
- request.get(options);
使用 options.agentOptions
在下面示例中, 我们调用一个需要 API, 它需要客户端 SSL 证书 (PEM 格式) 用密码保护私钥 (PEM 格式) 并禁用 SSLv3 协议:
- var fs = require('fs')
- , path = require('path')
- , certFile = path.resolve(__dirname, 'ssl/client.crt')
- , keyFile = path.resolve(__dirname, 'ssl/client.key')
- , request = require('request');
- var options = {
- url: 'https://api.some-server.com/',
- agentOptions: {
- cert: fs.readFileSync(certFile),
- key: fs.readFileSync(keyFile),
- // 或使用 `pfx` 属性替换 `cert` 和 `key` 使用私钥时, 证书和 CA 证书在 PFX 或 PKCS12 格式的文件中:
- // pfx: fs.readFileSync(pfxFilePath),
- passphrase: 'password',
- securityOptions: 'SSL_OP_NO_SSLv3'
- }
- };
- request.get(options);
如果强制使用 SSLv3, 则通过 secureProtocol 指定:
- request.get({
- url: 'https://api.some-server.com/',
- agentOptions: {
- secureProtocol: 'SSLv3_method'
- }
- });
10. 对 HAR 1.2 的支持
options.har 属性会重写 url.method, qs, headers, form, formData, body, json 的值, 当 request.postData.params[].fileName 的值不存在时, 会从硬盘文件构建 multipart 数据
当 HAC 请求匹配到指定规则时会执行验证检查, 如果未匹配到则会跳过:
- var request = require('request')
- request({
- // 将会忽略
- method: 'GET',
- uri: 'http://www.google.com',
- // HTTP 存档请求对象
- har: {
- url: 'http://www.mockbin.com/har',
- method: 'POST',
- headers: [
- {
- name: 'content-type',
- value: 'application/x-www-form-urlencoded'
- }
- ],
- postData: {
- mimeType: 'application/x-www-form-urlencoded',
- params: [
- {
- name: 'foo',
- value: 'bar'
- },
- {
- name: 'hello',
- value: 'world'
- }
- ]
- }
- }
- })
- // 一个 POST 请求会发送到 http://www.mockbin.com
- // 其请求体编码为 application/x-www-form-urlencoded, 发送内容:
- // foo=bar&hello=world
11. option 所有可用参数
request()的请求格式有如下两种形式:
- request(options, callback);
- // 或
- request(url, options, callback);
当使用 request.put(),request.post()等便捷方法进行请求时, 同样有如下两种形式:
- request.METHOD(options, callback);
- // 或
- request.METHOD(url, options, callback);
options 表示请求选项, 其中只有 > url/uri 是必须参数, 其它都是可选值. 下面是一些常用选项:
uri || url - 完整的 uri 字符串或可通过 url.parse()解析的 url 对象
baseUrl - 用于基本 uri 的远整字符串. 大多使用 request.defaults, 如: 对于大多数请求你相使用相同的域名. 如果 baseUrl 是 https://example.com/api/, 那么请求 / end/point?test=true 会匹配到 https://example.com/api/end/point?test=true; 当 baseUrl 指定后, uri 选项必须是字符串.
method - HTTP 请求方法(默认: "GET")
headers - HTTP 请求头 (默认: {})
查询字符串相关选项:
qs - 包含查询字符串值的对象, 会被添加到 uri 中
qsParseOptions - 用于 qs.parse 方法的选项对象, 或者传入 querystring.parse 方法用于 {sep:';', eq:':', options:{}} 格式的对象
qsStringifyOptions - 用于 qs.stringify 方法的选项对象, 或者传入用于 querystring.stringify 方法使用 {sep:';', eq:':', options:{}} 格式的选项.
useQuerystring - 如果 true, 使用 querystring 来解析查询字符串, 其它使用 qs (默认: false). 设置为 true 时, 你需要将数组序列化为 foo=bar&foo=baz 而默认为 foo[0]=bar&foo[1]=baz
请求体相关选项:
body - 可用于: PATCH, POST 和 PUT 请求的请求体(发送的数据). 必须是 Buffer, String 或 ReadStream. 如果 json 是 true, 则 body 必须是一个 JSON 化的对象.
form - 当通过对象或查询字符串发送数据时, 这一选项会设置 body 为包含发送值的查询字符串, 并添加自动 Content-type: application/x-www-form-urlencoded 请求头.
formData - 当发送 multipart/form-data 请求时使用. 参见前面的 Forms 一节.
multipart - 包含请求头与 body 属性的对象. 会发送一个 multipart/related 请求. 请求时使用. 参见 Forms. 也可以传入一个{chunked: false, data: []}, 其 chunked 用于指定发送请求的 chunked 转换编码. 如果非 chunked 请求,, 不允许使用使用具有请求体流的数据项.
preambleCRLF - 在 multipart/form-data 请求之前添加一个 newline/CRLF 边界描述
postambleCRLF - 在 multipart/form-data 请求之后添加一个 newline/CRLF 边界描述
json - 设置 body(请求体) 为 JSON 格式, 并添加 Content-type: application/json 请求头. 另外, 也会将响应体转换为 JSON 格式
jsonReviver - 一个 reviver 函数, 会传递给 JSON.parse() 方法用于解板响应体.
jsonReplacer - 一个 replacer 函数, 会传递给 JSON.stringify()方法用于序列化 JSON 请求体
认证相关选项:
auth - 包含 user || username, pass || password, 和 sendImmediately (可选)的哈希对象.
oauth - 用于 OAuth HMAC-SHA1 签名的选项
hawk - 用于 Hawk 签名的选项. credentials 键必须包含必要的签名信息, 参见 hawk 文档
aws - object 包含 AWS 签名信息. 需要有 key,secret 属性, 同样要有 bucket 选项, 除非已在路径中指定 bucket 或请求不使用 bucket (如 GET 服务). 如果要使用 AWS v4 版本, 则指定 sign_version 选项值为 4, 默认值为 2. 注意: 首先要 npm install aws4
httpSignature - 用于 HTTP Signature Scheme 的先项, 使用 Joyent's 签名库. keyId 和 key 属性必须同时指定
重定向相关选项:
followRedirect - 跟踪 HTTP 3xx 响应并重定向(默认: true). 这个属性也可以指定为一个获取单个 response 的函数, 如果重定向继续需要返回 true 其它情况返回 false
followAllRedirects - 跟踪非 GET 请求的 HTTP 3xx 响应(默认: false)
maxRedirects - 最大重定向跟踪数量(默认: 10)
removeRefererHeader - 当发生重定向进移聊 referer 头(默认: false). 注意: 如果设为 true,referer 头会设置为重定向链的初始请求.
编码 / 压缩相关选项:
encoding - 用于响应数据 setEncoding 头的编码. 如果 null, 则 body 会返回一个 Buffer. 任何情况下(除非设置为 undefined) 都会将 encoding 参数传递给 toString() 方法(默认为: utf8).
gzip - 如果为 true, 会添加一个 Accept-Encoding 头用于发送到服务器的请求内容的压缩和解压从服务器返回的数据
jar - 如果 true, 则记录使用的 cookies(或自定义 cookie jar)
代理相关选项:
agent - 用于 http(s).Agent 的代理实例
agentClass - 或指定代理类
agentOptions - 并传入代理选项. 注: 参见 HTTPS TLS/SSL API 文档 和 代理一节
forever - 如果设置为 true 会使用 forever-agent
pool - 描述用于请求的代理的对象. 如果此选项被省略, 请求将使用全局代理(当允许时). 否则, 请求将搜索您的自定义代理的池. 如果没有找到自定义代理, 将创建一个新的代理, 并将其添加到池中. 注意: pool 仅在指定 agent 选项后可用
maxSockets 属性同样可用于 pool 对象, 用于设置代理最大可创建的 sockets 连接数(如: pool: {maxSockets: Infinity})
当发送 multiple 请求时, 会创建一个新的 pool 对象, maxSockets 将不会按预期工作.
timeout - 超时时间(毫秒)
本地代理选项:
localAddress - 用于连接网络连接的本地接口
proxy - 使用的 HTTP 代理. 支持代理使用基本认证, 即认证信息通过 url 参数发送
strictSSL - 如果设置为 true, 则需要有效的 SSL 证书. 注意: 要使用自己的证书管理, 则需要指定一个所创建的代理的选项.
tunnel - 控制 HTTP CONNECT 连接的隧道, 可为以下值:
undefined (默认) - true 表示目标为 https, false 为其它方式
true - 总是通过 CONNECT 隧道请求连接到目的 代理
false - 使用 GET 请求方法请求目标.
proxyHeaderWhiteList - 发送到代理隧道的请求头白名单
proxyHeaderExclusiveList - 发送到代理隧道的请求头白名单, 仅用于代理而不是目标服务器
HAR 相关选项:
time - 为 true 时, 则请求 - 响应环 (包括所有重定向) 在指定毫秒内提供, 响应结果的回应时长为 elapsedTime
har - HAR 1.2 请求对象 Object, 将处理从 HAR 格式重写匹配值
callback - 或者通过选项对象传入请求回调函数. 回调函数包含以下 3 个参灵敏:
error - 错误对象(出错时存在, 通常由 http.ClientRequest 对象返回)
http.IncomingMessage 对象
response 响应体(String,Buffer 或 JSON 对象)
12. 便捷方法
Request 还可以使用以 HTTP 方法命名的便捷方法.
request.defaults(options)
返回一个正常请求 API 的包装器, 其默认值为所传递的 options 选项.
示例:
- // 使用 baseRequest() 进行请求是会设置一个'x-token' 请求头
- var baseRequest = request.defaults({
- headers: {'x-token': 'my-token'}
- })
- // 使用 specialRequest() 进行请求时, 会包含一个在 baseRequest 中设置的'x-token' 请求头
- // 还会有一个'special' 请求头
- var specialRequest = baseRequest.defaults({
- headers: {special: 'special value'}
- })
- request.put
与 request()方法相同, 但默认 method: "PUT"
- request.put(url)
- request.patch
与 request()方法相同, 但默认 method: "PATCH"
- request.patch(url)
- request.post
与 request()方法相同, 但默认 method: "POST"
- request.post(url)
- request.head
与 request()方法相同, 但默认 method: "HEAD"
- request.head(url)
- request.del / request.delete
与 request()方法相同, 但默认 method: "DELETE"
- request.del(url)
- request.delete(url)
- request.get
与 request()方法相同
- request.get(url)
- request.cookie
创建一个新 Cookie
- request.cookie('key1=value1')
- request.jar
创建一个新 Cookie Jar
request.jar()
注: Cookie Jar 用于保存所访问网站的 Cookie 信息
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' 文件必须已经存在
- 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", ...}, ...]
- })
来源: http://www.jb51.net/article/113061.htm