国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > JavaScript > 正文

詳解node HTTP請(qǐng)求客戶端 - Request

2019-11-19 16:39:27
字體:
供稿:網(wǎng)友

Request是一個(gè)Node.jsNPM模塊,它是一個(gè)HTTP客戶端,使用簡單功能確十分強(qiáng)大。我們可以用它來實(shí)現(xiàn)HTTP響應(yīng)流的轉(zhuǎn)接、模擬Form表單提交、支持HTTP認(rèn)證、OAuth登錄、自定義請(qǐng)求頭等。下面我們來對(duì)這個(gè)模塊做一個(gè)完整的介紹:

1. 安裝及簡單使用

安裝request模塊:

npm install request

Request設(shè)計(jì)為用最簡單的方法發(fā)送HTTP請(qǐng)求,它還支持HTTPS請(qǐng)求和自動(dòng)重定向跟蹤:

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()方法來發(fā)送HTTP請(qǐng)求,在不指定請(qǐng)求選項(xiàng)option時(shí),默認(rèn)為GET。在上面請(qǐng)求中,對(duì)URLhttp://www.baidu.com

會(huì)301重定向到http://www.baidu.com。而Request會(huì)自動(dòng)跟蹤URL重定向請(qǐng)求,默認(rèn)支持10次重定向跟蹤。

2. 流(stream)操作

Node.js原生HTTP模塊實(shí)現(xiàn)了對(duì)HTTP請(qǐng)求和響應(yīng)對(duì)象的流操作,Request同樣支持基于流的操作。

如,可以將任何響應(yīng)流通過pipe轉(zhuǎn)接到一個(gè)文件流:

復(fù)制代碼 代碼如下:

request('http://google.com/doodle.png').pipe(fs.createWriteStream('doodle.png'))

同樣,可以將一個(gè)讀取的文件流轉(zhuǎn)接到PUT或POST請(qǐng)求中。這個(gè)方法會(huì)自動(dòng)檢查文件擴(kuò)展名,并設(shè)置一個(gè)與文件擴(kuò)展名對(duì)應(yīng)的content-type(當(dāng)該請(qǐng)求頭未設(shè)置時(shí)):

復(fù)制代碼 代碼如下:

fs.createReadStream('file.json').pipe(request.put('http://mysite.com/obj.json'))

Request也支持pipe到它自己。這樣操作時(shí),content-type和content-length將被傳遞到其后的PUT請(qǐng)求中:

復(fù)制代碼 代碼如下:

request.get('http://google.com/img.png').pipe(request.put('http://mysite.com/img.png'))

與原生HTTP客戶端一樣,Request在收到請(qǐng)求響應(yīng)時(shí)會(huì)發(fā)送一個(gè)'response'。事件回調(diào)函數(shù)中會(huì)包含一個(gè)response參數(shù),它是一個(gè)http.IncomingMessage實(shí)例:

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'))

當(dāng)請(qǐng)求發(fā)生錯(cuò)誤時(shí),可以簡單的通過監(jiān)聽error事件來處理:

request .get('http://mysite.com/doodle.png') .on('error', function(err) { console.log(err) }) .pipe(fs.createWriteStream('doodle.png'))

發(fā)揮一個(gè)想象:

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()方法將一個(gè)http.ServerRequest實(shí)例轉(zhuǎn)換到一個(gè)http.ServerResponse。HTTP請(qǐng)求方法、請(qǐng)求頭、請(qǐng)求體數(shù)據(jù)會(huì)被發(fā)送:

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()返回的目標(biāo)流,在Nodev0.5.x+版本中,可以寫到一行:

復(fù)制代碼 代碼如下:

req.pipe(request('http://mysite.com/doodle.png')).pipe(resp)

而所有這些,沒有一個(gè)新功能會(huì)與原功能有沖突,只是對(duì)其進(jìn)行了擴(kuò)展。還可以使用HTTP代理,請(qǐng)求會(huì)被自動(dòng)重定向并跟蹤:

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會(huì)引用multipartAPI。

application/x-www-form-urlencoded (URL編碼的Form)

URL編碼的Form很簡單:

request.post('http://service.com/upload', {form:{key:'value'}})// orrequest.post('http://service.com/upload').form({key:'value'})// orrequest.post({url:'http://service.com/upload', form: {key:'value'}}, function(err,httpResponse,body){ /* ... */ })

multipart/form-data (Multipart Form 上傳)

對(duì)于multipart/form-dataFrom文件上傳,Request使用了form-data處理。大多數(shù)情況,可以通過formData選項(xiàng)添加上傳文件:

var formData = { // 鍵-值對(duì)簡單值 my_field: 'my_value', // 使用 Buffers 添加數(shù)據(jù) my_buffer: new Buffer([1, 2, 3]), // 使用 Streams 添加數(shù)據(jù) my_file: fs.createReadStream(__dirname + '/unicycle.jpg'), // 通過數(shù)組添加 multiple 值 attachments: [ fs.createReadStream(__dirname + '/attachment1.jpg'), fs.createReadStream(__dirname + '/attachment2.jpg') ], // 添加可選的 meta-data 使用: {value: DATA, options: OPTIONS} // 對(duì)于一些流類型,需要提供手工添加 "file"-關(guān)聯(lián)  // 詳細(xì)查看 `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);});

在一些更加高級(jí)的使用中,可以通過其自身的如r.form()來訪問Form數(shù)據(jù):

// NOTE: Advanced use-case, for normal use see 'formData' usage abovevar 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實(shí)現(xiàn)中,需要在multipart/related的之前、之后或前后同時(shí)添加一個(gè)newline/CRLF(通過multipart選項(xiàng))。特別是在.NET WebAPI 4.0中,需要將preambleCRLF設(shè)置為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認(rèn)證

在一些HTTP請(qǐng)求中,需要對(duì)請(qǐng)求對(duì)象進(jìn)行身份驗(yàn)證。Request提供了多種身份驗(yàn)證方式:

request.get('http://some.server.com/').auth('username', 'password', false);// orrequest.get('http://some.server.com/', { 'auth': { 'user': 'username', 'pass': 'password', 'sendImmediately': false }});// orrequest.get('http://some.server.com/').auth(null, null, true, 'bearerToken');// orrequest.get('http://some.server.com/', { 'auth': { 'bearer': 'bearerToken' }});

當(dāng)使用auth選項(xiàng)進(jìn),其可包含以下值:

  1. user || username
  2. pass || password
  3. sendImmediately (可選)
  4. bearer (可選)

而對(duì)于最終調(diào)用的auth(username, password, sendImmediately, bearer)方法來說,sendImmediately默認(rèn)為true,這會(huì)導(dǎo)致一個(gè) basic 或 bearer 認(rèn)證頭會(huì)被發(fā)送。如果sendImmediately設(shè)置為false,request會(huì)在收到401狀態(tài)后嘗試使用一個(gè)合適的認(rèn)證頭。

注意,也可以基于RFC 1738標(biāo)準(zhǔn),在URL中添加認(rèn)證信息。簡單的是使用方式是在主機(jī)的@符號(hào)前添加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頭

如果需要設(shè)置自定義的HTTP請(qǐng)求頭,如:User-Agent,可以通過options對(duì)象設(shè)置。

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。其默認(rèn)使用的簽名算法為 HMAC-SHA1:

// OAuth1.0 - 3-legged server side flow (Twitter example)// step 1var 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 簽名時(shí),可傳入如下一個(gè)OAuth對(duì)象:

  1. 指定signature_method : 'RSA-SHA1'
  2. 代替consumer_secret,指定private_key字符串為 PEM format

而使用PLAINTEXT 簽名,可傳入如下一個(gè)OAuth對(duì)象:

  1. 指定signature_method : 'PLAINTEXT'

7. 代理

如果指定proxy(代理)選項(xiàng)后,所有的請(qǐng)求(及其后的重定向)都會(huì)連接到該代理服務(wù)器。

如果終端是一個(gè)httpsURL,代理會(huì)使用CONNECT請(qǐng)求連接到代理服務(wù)器。

首先會(huì)生成類似如下一個(gè)請(qǐng)求:

HTTP/1.1 CONNECT endpoint-server.com:80Host: proxy-server.comUser-Agent: whatever user agent you specify

然后建立一個(gè)到endpoint-server(終端服務(wù)器)的80端口的TCP連接,并按如下返回響應(yīng):

HTTP/1.1 200 OK

默認(rèn)情況下,當(dāng)代理使用http進(jìn)行通訊時(shí),request會(huì)簡單的生成一個(gè)標(biāo)準(zhǔn)的http代理請(qǐng)求。如,會(huì)像如下這樣生成一個(gè)請(qǐng)求:

HTTP/1.1 GET http://endpoint-server.com/some-urlHost: proxy-server.comOther-Headers: all go hererequest body or whatever

通過proxyHeaderExclusiveList選項(xiàng)可以明確指定一些代理頭,默認(rèn)會(huì)按如下方式設(shè)置:

acceptaccept-charsetaccept-encodingaccept-languageaccept-rangescache-controlcontent-encodingcontent-languagecontent-lengthcontent-locationcontent-md5content-rangecontent-typeconnectiondateexpectmax-forwardspragmaproxy-authorizationreferertetransfer-encodinguser-agentvia

8. UNIX域套接字

request支持到UNIX域套接字的請(qǐng)求:

/* Pattern */ 'http://unix:SOCKET:PATH'/* Example */ request.get('http://unix:/absolute/path/to/unix.socket:/request/path')

注意:SOCKET應(yīng)該是一個(gè)到文件系統(tǒng)根目錄的絕對(duì)路徑。

 9. TLS/SSL協(xié)議

對(duì)于使用了TLS/SSL等安全協(xié)議的請(qǐng)求,可以使用相關(guān)選項(xiàng)如cert、key、passphrase也可以使用agentOptions選項(xiàng)甚至使用https.globalAgent.options來設(shè)置:

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

在下面示例中,我們調(diào)用一個(gè)需要API,它需要客戶端SSL證書(PEM格式)用密碼保護(hù)私鑰(PEM格式)并禁用SSLv3協(xié)議:

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`使用私鑰時(shí),證書和CA證書在 PFX 或 PKCS12 格式的文件中: // pfx: fs.readFileSync(pfxFilePath), passphrase: 'password', securityOptions: 'SSL_OP_NO_SSLv3' }};request.get(options);

如果強(qiáng)制使用SSLv3,則通過secureProtocol指定:

 request.get({ url: 'https://api.some-server.com/', agentOptions: { secureProtocol: 'SSLv3_method' }});

10. 對(duì)HAR 1.2的支持

options.har屬性會(huì)重寫url。method, qs, headers, form, formData, body, json的值,當(dāng)request.postData.params[].fileName的值不存在時(shí),會(huì)從硬盤文件構(gòu)建 multipart 數(shù)據(jù)

當(dāng)HAC 請(qǐng)求匹配到指定規(guī)則時(shí)會(huì)執(zhí)行驗(yàn)證檢查,如果未匹配到則會(huì)跳過:

var request = require('request') request({ // 將會(huì)忽略 method: 'GET', uri: 'http://www.google.com', // HTTP 存檔請(qǐng)求對(duì)象 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'  } ] } } }) // 一個(gè) POST 請(qǐng)求會(huì)發(fā)送到 http://www.mockbin.com // 其請(qǐng)求體編碼為 application/x-www-form-urlencoded,發(fā)送內(nèi)容: // foo=bar&hello=world

 11. option所有可用參數(shù)

request()的請(qǐng)求格式有如下兩種形式:

request(options, callback);// 或request(url, options, callback);

當(dāng)使用request.put()、request.post()等便捷方法進(jìn)行請(qǐng)求時(shí),同樣有如下兩種形式:

request.METHOD(options, callback);// 或request.METHOD(url, options, callback);

options表示請(qǐng)求選項(xiàng),其中只有>url/uri是必須參數(shù),其它都是可選值。下面是一些常用選項(xiàng):

  1. uri || url - 完整的uri字符串或可通過url.parse()解析的url對(duì)象
  2. baseUrl - 用于基本uri的遠(yuǎn)整字符串。大多使用request.defaults,如:對(duì)于大多數(shù)請(qǐng)求你相使用相同的域名。如果baseUrl 是 https://example.com/api/,那么請(qǐng)求/end/point?test=true 會(huì)匹配到https://example.com/api/end/point?test=true;當(dāng)baseUrl指定后,uri選項(xiàng)必須是字符串。
  3. method - HTTP請(qǐng)求方法(默認(rèn): "GET")
  4. headers - HTTP請(qǐng)求頭 (默認(rèn): {})

查詢字符串相關(guān)選項(xiàng):

  1. qs - 包含查詢字符串值的對(duì)象,會(huì)被添加到uri中
  2. qsParseOptions - 用于qs.parse方法的選項(xiàng)對(duì)象,或者傳入querystring.parse方法用于{sep:';', eq:':', options:{}}格式的對(duì)象
  3. qsStringifyOptions - 用于qs.stringify 方法的選項(xiàng)對(duì)象,或者傳入用于querystring.stringify 方法使用{sep:';', eq:':', options:{}}格式的選項(xiàng)。
  4. useQuerystring - 如果true,使用querystring 來解析查詢字符串,其它使用qs (默認(rèn): false)。設(shè)置為true時(shí),你需要將數(shù)組序列化為foo=bar&foo=baz 而默認(rèn)為 foo[0]=bar&foo[1]=baz

請(qǐng)求體相關(guān)選項(xiàng):

  1. body - 可用于:PATCH, POST 和 PUT 請(qǐng)求的請(qǐng)求體(發(fā)送的數(shù)據(jù))。必須是Buffer, String 或 ReadStream。如果json 是 true,則body 必須是一個(gè)JSON化的對(duì)象。
  2. form - 當(dāng)通過對(duì)象或查詢字符串發(fā)送數(shù)據(jù)時(shí),這一選項(xiàng)會(huì)設(shè)置body 為包含發(fā)送值的查詢字符串,并添加自動(dòng)Content-type: application/x-www-form-urlencoded請(qǐng)求頭。
  3. formData - 當(dāng)發(fā)送multipart/form-data請(qǐng)求時(shí)使用。參見前面的Forms 一節(jié)。
  4. multipart - 包含請(qǐng)求頭與body屬性的對(duì)象。會(huì)發(fā)送一個(gè)multipart/related請(qǐng)求。請(qǐng)求時(shí)使用。參見Forms。 也可以傳入一個(gè){chunked: false, data: []},其 chunked 用于指定發(fā)送請(qǐng)求的 chunked 轉(zhuǎn)換編碼。如果非chunked請(qǐng)求,,不允許使用使用具有請(qǐng)求體流的數(shù)據(jù)項(xiàng)。
  5. preambleCRLF - 在multipart/form-data請(qǐng)求之前添加一個(gè) newline/CRLF 邊界描述
  6. postambleCRLF - 在multipart/form-data請(qǐng)求之后添加一個(gè) newline/CRLF 邊界描述
  7. json - 設(shè)置 body(請(qǐng)求體) 為JSON格式,并添加Content-type: application/json請(qǐng)求頭。另外,也會(huì)將響應(yīng)體轉(zhuǎn)換為JSON格式
  8. jsonReviver - 一個(gè)reviver函數(shù),會(huì)傳遞給JSON.parse() 方法用于解板響應(yīng)體。
  9. jsonReplacer - 一個(gè) replacer 函數(shù),會(huì)傳遞給JSON.stringify()方法用于序列化JSON請(qǐng)求體

認(rèn)證相關(guān)選項(xiàng):

  1. auth - 包含 user || username, pass || password, 和 sendImmediately (可選)的哈希對(duì)象。
  2. oauth - 用于 OAuth HMAC-SHA1 簽名的選項(xiàng)
  3. hawk - 用于Hawk 簽名的選項(xiàng)。credentials 鍵必須包含必要的簽名信息,參見hawk文檔
  4. aws - object 包含 AWS 簽名信息。需要有key、secret屬性,同樣要有bucket選項(xiàng),除非已在路徑中指定bucket或請(qǐng)求不使用 bucket (如 GET 服務(wù))。如果要使用 AWS v4版本,則指定sign_version 選項(xiàng)值為 4,默認(rèn)值為2。注意: 首先要 npm install aws4
  5. httpSignature - 用于HTTP Signature Scheme的先項(xiàng),使用Joyent's簽名庫。keyId 和 key 屬性必須同時(shí)指定

重定向相關(guān)選項(xiàng):

  1. followRedirect - 跟蹤 HTTP 3xx 響應(yīng)并重定向(默認(rèn): true)。這個(gè)屬性也可以指定為一個(gè)獲取單個(gè)response的函數(shù),如果重定向繼續(xù)需要返回true 其它情況返回 false
  2. followAllRedirects - 跟蹤非GET請(qǐng)求的 HTTP 3xx 響應(yīng)(默認(rèn): false)
  3. maxRedirects - 最大重定向跟蹤數(shù)量(默認(rèn): 10)
  4. removeRefererHeader - 當(dāng)發(fā)生重定向進(jìn)移聊referer頭(默認(rèn): false)。注意: 如果設(shè)為 true,referer頭會(huì)設(shè)置為重定向鏈的初始請(qǐng)求。

編碼/壓縮相關(guān)選項(xiàng):

  1. encoding - 用于響應(yīng)數(shù)據(jù) setEncoding 頭的編碼。如果null,則 body 會(huì)返回一個(gè) Buffer。任何情況下(除非設(shè)置為undefined) 都會(huì)將encoding 參數(shù)傳遞給 toString() 方法(默認(rèn)為:utf8)。
  2. gzip - 如果為 true,會(huì)添加一個(gè)Accept-Encoding 頭用于發(fā)送到服務(wù)器的請(qǐng)求內(nèi)容的壓縮和解壓從服務(wù)器返回的數(shù)據(jù)
  3. jar - 如果 true,則記錄使用的 cookies(或自定義 cookie jar)

代理相關(guān)選項(xiàng):

  1. agent - 用于http(s).Agent 的代理實(shí)例
  2. agentClass - 或指定代理類
  3. agentOptions - 并傳入代理選項(xiàng)。注: 參見 HTTPS TLS/SSL API文檔 和 代理一節(jié)
  4. forever - 如果設(shè)置為 true 會(huì)使用 forever-agent
  5. pool - 描述用于請(qǐng)求的代理的對(duì)象。如果此選項(xiàng)被省略,請(qǐng)求將使用全局代理(當(dāng)允許時(shí))。否則,請(qǐng)求將搜索您的自定義代理的池。如果沒有找到自定義代理,將創(chuàng)建一個(gè)新的代理,并將其添加到池中。注意: pool 僅在指定agent選項(xiàng)后可用
    1. maxSockets屬性同樣可用于pool對(duì)象,用于設(shè)置代理最大可創(chuàng)建的 sockets 連接數(shù)(如:pool: {maxSockets: Infinity})
    2. 當(dāng)發(fā)送 multiple 請(qǐng)求時(shí),會(huì)創(chuàng)建一個(gè)新的pool 對(duì)象,maxSockets 將不會(huì)按預(yù)期工作。
    3. timeout - 超時(shí)時(shí)間(毫秒)

本地代理選項(xiàng):

  1. localAddress - 用于連接網(wǎng)絡(luò)連接的本地接口
  2. proxy - 使用的HTTP代理。支持代理使用基本認(rèn)證,即認(rèn)證信息通過url參數(shù)發(fā)送
  3. strictSSL - 如果設(shè)置為true,則需要有效的 SSL證書。注意: 要使用自己的證書管理,則需要指定一個(gè)所創(chuàng)建的代理的選項(xiàng)。
  4. tunnel - 控制 HTTP CONNECT 連接的隧道,可為以下值:
    1. undefined (默認(rèn)) - true 表示目標(biāo)為 https, false 為其它方式
    2. true - 總是通過CONNECT隧道請(qǐng)求連接到目的 代理
    3. false - 使用GET請(qǐng)求方法請(qǐng)求目標(biāo).
  5. proxyHeaderWhiteList -發(fā)送到代理隧道的請(qǐng)求頭白名單
  6. proxyHeaderExclusiveList - 發(fā)送到代理隧道的請(qǐng)求頭白名單,僅用于代理而不是目標(biāo)服務(wù)器

HAR相關(guān)選項(xiàng):

  1. time - 為true時(shí),則請(qǐng)求-響應(yīng)環(huán)(包括所有重定向)在指定毫秒內(nèi)提供,響應(yīng)結(jié)果的回應(yīng)時(shí)長為elapsedTime
  2. har - HAR 1.2 請(qǐng)求對(duì)象 Object,將處理從HAR格式重寫匹配值
  3. callback - 或者通過選項(xiàng)對(duì)象傳入請(qǐng)求回調(diào)函數(shù)。回調(diào)函數(shù)包含以下3個(gè)參靈敏:
    1. error - 錯(cuò)誤對(duì)象(出錯(cuò)時(shí)存在,通常由http.ClientRequest對(duì)象返回)
    2. http.IncomingMessage對(duì)象
    3. response 響應(yīng)體(String、Buffer或JSON 對(duì)象)

12. 便捷方法

Request還可以使用以HTTP方法命名的便捷方法。

request.defaults(options)

返回一個(gè)正常請(qǐng)求API的包裝器,其默認(rèn)值為所傳遞的options選項(xiàng)。

示例:

// 使用 baseRequest() 進(jìn)行請(qǐng)求是會(huì)設(shè)置一個(gè) 'x-token' 請(qǐng)求頭var baseRequest = request.defaults({ headers: {'x-token': 'my-token'}})// 使用 specialRequest() 進(jìn)行請(qǐng)求時(shí),會(huì)包含一個(gè)在 baseRequest 中設(shè)置的 'x-token' 請(qǐng)求頭// 還會(huì)有一個(gè) 'special' 請(qǐng)求頭var specialRequest = baseRequest.defaults({ headers: {special: 'special value'}})

request.put

與request()方法相同,但默認(rèn)method: "PUT"

request.put(url)

request.patch

與request()方法相同,但默認(rèn)method: "PATCH"

request.patch(url)

request.post

與request()方法相同,但默認(rèn)method: "POST"

request.post(url)

request.head

與request()方法相同,但默認(rèn)method: "HEAD"

request.head(url)

request.del / request.delete

與request()方法相同,但默認(rèn)method: "DELETE"

request.del(url)request.delete(url)

request.get

與request()方法相同

request.get(url)

request.cookie

創(chuàng)建一個(gè)新Cookie

request.cookie('key1=value1')

request.jar

創(chuàng)建一個(gè)新Cookie Jar

request.jar()

注:Cookie Jar用于保存所訪問網(wǎng)站的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)  } } )

 為了保持向后兼容,響應(yīng)壓縮默認(rèn)不會(huì)啟用。要訪問gzip壓縮的響應(yīng),需要將gzip選項(xiàng)設(shè)置為true。這樣數(shù)據(jù)體會(huì)通過request自動(dòng)解壓縮,而響應(yīng)的對(duì)象將未包含壓縮數(shù)據(jù)。

var request = require('request')request( { method: 'GET' , uri: 'http://www.google.com' , gzip: true }, function (error, response, body) { // body 是解壓縮后的 response 響應(yīng)體 console.log('server encoded the data as: ' + (response.headers['content-encoding'] || 'identity')) console.log('the decoded data is: ' + body) }).on('data', function(data) { // 收到的是解壓縮后的數(shù)據(jù) console.log('decoded chunk: ' + data)}).on('response', function(response) { // 未修改 http.IncomingMessage object response.on('data', function(data) { // 收到的是壓縮數(shù)據(jù) console.log('received ' + data.length + ' bytes of compressed data') })})

 Cookie默認(rèn)是未啟用的,可以通過將jar選項(xiàng)設(shè)置為true來啟用Cookie:

var request = request.defaults({jar: true})request('http://www.google.com', function () { request('http://images.google.com')})

使用自定義的Cookie Jar,可以將jar選項(xiàng)設(shè)置為一個(gè)request.jar()實(shí)例:

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存儲(chǔ),可以做為request.jar()的參數(shù)傳入:

var FileCookieStore = require('tough-cookie-filestore');// 這時(shí) 'cookies.json' 文件必須已經(jīng)存在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存儲(chǔ)必須是一個(gè)tough-cookie且必須支持同步操作。

在請(qǐng)求完成后,檢查你的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", ...}, ...]})

 以上就是本文的全部內(nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持武林網(wǎng)。

發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 吴堡县| 牙克石市| 永昌县| 新竹市| 海盐县| 伽师县| 金川县| 河南省| 吉水县| 神木县| 华安县| 遂宁市| 祁连县| 新闻| 若尔盖县| 始兴县| 哈尔滨市| 侯马市| 曲麻莱县| 绵阳市| 南木林县| 闽侯县| 紫金县| 延庆县| 龙游县| 廉江市| 寿光市| 岑溪市| 德庆县| 中宁县| 绿春县| 东莞市| 锦州市| 始兴县| 盐亭县| 枣强县| 屏山县| 延边| 新沂市| 巫山县| 大渡口区|