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è)文件流:
同樣,可以將一個(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í)):
Request也支持pipe到它自己。這樣操作時(shí),content-type和content-length將被傳遞到其后的PUT請(qǐng)求中:
與原生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+版本中,可以寫到一行:
而所有這些,沒有一個(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),其可包含以下值:
而對(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ì)象:
而使用PLAINTEXT 簽名,可傳入如下一個(gè)OAuth對(duì)象:
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=world11. 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):
查詢字符串相關(guān)選項(xiàng):
請(qǐng)求體相關(guān)選項(xiàng):
認(rèn)證相關(guān)選項(xiàng):
重定向相關(guān)選項(xiàng):
編碼/壓縮相關(guān)選項(xiàng):
代理相關(guān)選項(xiàng):
本地代理選項(xiàng):
HAR相關(guān)選項(xiàng):
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)。
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注