這期內(nèi)容當(dāng)中小編將會(huì)給大家?guī)碛嘘P(guān)node中怎么利用Request實(shí)現(xiàn)一個(gè)HTTP請(qǐng)求客戶端,文章內(nèi)容豐富且以專業(yè)的角度為大家分析和敘述,閱讀完這篇文章希望大家可以有所收獲。

成都創(chuàng)新互聯(lián)長期為上1000+客戶提供的網(wǎng)站建設(shè)服務(wù),團(tuán)隊(duì)從業(yè)經(jīng)驗(yàn)10年,關(guān)注不同地域、不同群體,并針對(duì)不同對(duì)象提供差異化的產(chǎn)品和服務(wù);打造開放共贏平臺(tái),與合作伙伴共同營造健康的互聯(lián)網(wǎng)生態(tài)環(huán)境。為華容企業(yè)提供專業(yè)的成都網(wǎng)站設(shè)計(jì)、成都網(wǎng)站制作、外貿(mào)網(wǎng)站建設(shè),華容網(wǎng)站改版等技術(shù)服務(wù)。擁有十載豐富建站經(jīng)驗(yàn)和眾多成功案例,為您定制開發(fā)。
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'}})
// 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 上傳)
對(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 above
var r = request.post('/upload/otherpic46/74489.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);
// 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'
}
});當(dāng)使用auth選項(xiàng)進(jìn),其可包含以下值:
user || username
pass || password
sendImmediately (可選)
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:
// OAuth2.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 簽名時(shí),可傳入如下一個(gè)OAuth對(duì)象:
指定signature_method : 'RSA-SHA1'
代替consumer_secret,指定private_key字符串為 PEM format
而使用PLAINTEXT 簽名,可傳入如下一個(gè)OAuth對(duì)象:
指定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:80 Host: proxy-server.com User-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-url Host: proxy-server.com Other-Headers: all go here request body or whatever
通過proxyHeaderExclusiveList選項(xiàng)可以明確指定一些代理頭,默認(rèn)會(huì)按如下方式設(shè)置:
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域套接字的請(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):
uri || url - 完整的uri字符串或可通過url.parse()解析的url對(duì)象
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)必須是字符串。
method - HTTP請(qǐng)求方法(默認(rèn): "GET")
headers - HTTP請(qǐng)求頭 (默認(rèn): {})
查詢字符串相關(guān)選項(xiàng):
qs - 包含查詢字符串值的對(duì)象,會(huì)被添加到uri中
qsParseOptions - 用于qs.parse方法的選項(xiàng)對(duì)象,或者傳入querystring.parse方法用于{sep:';', eq:':', options:{}}格式的對(duì)象
qsStringifyOptions - 用于qs.stringify 方法的選項(xiàng)對(duì)象,或者傳入用于querystring.stringify 方法使用{sep:';', eq:':', options:{}}格式的選項(xiàng)。
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):
body - 可用于:PATCH, POST 和 PUT 請(qǐng)求的請(qǐng)求體(發(fā)送的數(shù)據(jù))。必須是Buffer, String 或 ReadStream。如果json 是 true,則body 必須是一個(gè)JSON化的對(duì)象。
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)求頭。
formData - 當(dāng)發(fā)送multipart/form-data請(qǐng)求時(shí)使用。參見前面的Forms 一節(jié)。
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)。
preambleCRLF - 在multipart/form-data請(qǐng)求之前添加一個(gè) newline/CRLF 邊界描述
postambleCRLF - 在multipart/form-data請(qǐng)求之后添加一個(gè) newline/CRLF 邊界描述
json - 設(shè)置 body(請(qǐng)求體) 為JSON格式,并添加Content-type: application/json請(qǐng)求頭。另外,也會(huì)將響應(yīng)體轉(zhuǎn)換為JSON格式
jsonReviver - 一個(gè)reviver函數(shù),會(huì)傳遞給JSON.parse() 方法用于解板響應(yīng)體。
jsonReplacer - 一個(gè) replacer 函數(shù),會(huì)傳遞給JSON.stringify()方法用于序列化JSON請(qǐng)求體
認(rèn)證相關(guān)選項(xiàng):
auth - 包含 user || username, pass || password, 和 sendImmediately (可選)的哈希對(duì)象。
oauth - 用于 OAuth HMAC-SHA1 簽名的選項(xiàng)
hawk - 用于Hawk 簽名的選項(xiàng)。credentials 鍵必須包含必要的簽名信息,參見hawk文檔
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
httpSignature - 用于HTTP Signature Scheme的先項(xiàng),使用Joyent's簽名庫。keyId 和 key 屬性必須同時(shí)指定
重定向相關(guān)選項(xiàng):
followRedirect - 跟蹤 HTTP 3xx 響應(yīng)并重定向(默認(rèn): true)。這個(gè)屬性也可以指定為一個(gè)獲取單個(gè)response的函數(shù),如果重定向繼續(xù)需要返回true 其它情況返回 false
followAllRedirects - 跟蹤非GET請(qǐng)求的 HTTP 3xx 響應(yīng)(默認(rèn): false)
maxRedirects - 最大重定向跟蹤數(shù)量(默認(rèn): 10)
removeRefererHeader - 當(dāng)發(fā)生重定向進(jìn)移聊referer頭(默認(rèn): false)。注意: 如果設(shè)為 true,referer頭會(huì)設(shè)置為重定向鏈的初始請(qǐng)求。
編碼/壓縮相關(guān)選項(xiàng):
encoding - 用于響應(yīng)數(shù)據(jù) setEncoding 頭的編碼。如果null,則 body 會(huì)返回一個(gè) Buffer。任何情況下(除非設(shè)置為undefined) 都會(huì)將encoding 參數(shù)傳遞給 toString() 方法(默認(rèn)為:utf8)。
gzip - 如果為 true,會(huì)添加一個(gè)Accept-Encoding 頭用于發(fā)送到服務(wù)器的請(qǐng)求內(nèi)容的壓縮和解壓從服務(wù)器返回的數(shù)據(jù)
jar - 如果 true,則記錄使用的 cookies(或自定義 cookie jar)
代理相關(guān)選項(xiàng):
agent - 用于http(s).Agent 的代理實(shí)例
agentClass - 或指定代理類
agentOptions - 并傳入代理選項(xiàng)。注: 參見 HTTPS TLS/SSL API文檔 和 代理一節(jié)
forever - 如果設(shè)置為 true 會(huì)使用 forever-agent
pool - 描述用于請(qǐng)求的代理的對(duì)象。如果此選項(xiàng)被省略,請(qǐng)求將使用全局代理(當(dāng)允許時(shí))。否則,請(qǐng)求將搜索您的自定義代理的池。如果沒有找到自定義代理,將創(chuàng)建一個(gè)新的代理,并將其添加到池中。注意: pool 僅在指定agent選項(xiàng)后可用
maxSockets屬性同樣可用于pool對(duì)象,用于設(shè)置代理最大可創(chuàng)建的 sockets 連接數(shù)(如:pool: {maxSockets: Infinity})
當(dāng)發(fā)送 multiple 請(qǐng)求時(shí),會(huì)創(chuàng)建一個(gè)新的pool 對(duì)象,maxSockets 將不會(huì)按預(yù)期工作。
timeout - 超時(shí)時(shí)間(毫秒)
本地代理選項(xiàng):
localAddress - 用于連接網(wǎng)絡(luò)連接的本地接口
proxy - 使用的HTTP代理。支持代理使用基本認(rèn)證,即認(rèn)證信息通過url參數(shù)發(fā)送
strictSSL - 如果設(shè)置為true,則需要有效的 SSL證書。注意: 要使用自己的證書管理,則需要指定一個(gè)所創(chuàng)建的代理的選項(xiàng)。
tunnel - 控制 HTTP CONNECT 連接的隧道,可為以下值:
undefined (默認(rèn)) - true 表示目標(biāo)為 https, false 為其它方式
true - 總是通過CONNECT隧道請(qǐng)求連接到目的 代理
false - 使用GET請(qǐng)求方法請(qǐng)求目標(biāo).
proxyHeaderWhiteList -發(fā)送到代理隧道的請(qǐng)求頭白名單
proxyHeaderExclusiveList - 發(fā)送到代理隧道的請(qǐng)求頭白名單,僅用于代理而不是目標(biāo)服務(wù)器
HAR相關(guān)選項(xiàng):
time - 為true時(shí),則請(qǐng)求-響應(yīng)環(huán)(包括所有重定向)在指定毫秒內(nèi)提供,響應(yīng)結(jié)果的回應(yīng)時(shí)長為elapsedTime
har - HAR 1.2 請(qǐng)求對(duì)象 Object,將處理從HAR格式重寫匹配值
callback - 或者通過選項(xiàng)對(duì)象傳入請(qǐng)求回調(diào)函數(shù)。回調(diào)函數(shù)包含以下3個(gè)參靈敏:
error - 錯(cuò)誤對(duì)象(出錯(cuò)時(shí)存在,通常由http.ClientRequest對(duì)象返回)
http.IncomingMessage對(duì)象
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", ...}, ...]
})上述就是小編為大家分享的node中怎么利用Request實(shí)現(xiàn)一個(gè)HTTP請(qǐng)求客戶端了,如果剛好有類似的疑惑,不妨參照上述分析進(jìn)行理解。如果想知道更多相關(guān)知識(shí),歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道。
網(wǎng)站名稱:node中怎么利用Request實(shí)現(xiàn)一個(gè)HTTP請(qǐng)求客戶端
鏈接地址:http://chinadenli.net/article28/ipccjp.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供App設(shè)計(jì)、網(wǎng)站排名、小程序開發(fā)、網(wǎng)站設(shè)計(jì)公司、定制開發(fā)、用戶體驗(yàn)
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)