在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
开源软件名称:request/request开源软件地址:https://github.com/request/request开源编程语言:JavaScript 99.0%开源软件介绍:Deprecated!As of Feb 11th 2020, request is fully deprecated. No new changes are expected to land. In fact, none have landed for some time. For more information about why request is deprecated and possible alternatives refer to this issue. Request - Simplified HTTP clientSuper simple to useRequest is designed to be the simplest way possible to make http calls. It supports HTTPS and follows redirects by default. const request = require('request');
request('http://www.google.com', function (error, response, body) {
console.error('error:', error); // Print the error if one occurred
console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received
console.log('body:', body); // Print the HTML for the Google homepage.
}); Table of contents
Request also offers convenience methods like
StreamingYou can stream any response to a file stream. request('http://google.com/doodle.png').pipe(fs.createWriteStream('doodle.png')) You can also stream a file to a PUT or POST request. This method will also check the file extension against a mapping of file extensions to content-types (in this case fs.createReadStream('file.json').pipe(request.put('http://mysite.com/obj.json')) Request can also request.get('http://google.com/img.png').pipe(request.put('http://mysite.com/img.png')) Request emits a "response" event when a response is received. The 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')) To easily handle errors when streaming requests, listen to the request
.get('http://mysite.com/doodle.png')
.on('error', function(err) {
console.error(err)
})
.pipe(fs.createWriteStream('doodle.png')) Now let’s get fancy. 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)
}
}
}) You can also http.createServer(function (req, resp) {
if (req.url === '/doodle.png') {
const x = request('http://mysite.com/doodle.png')
req.pipe(x)
x.pipe(resp)
}
}) And since req.pipe(request('http://mysite.com/doodle.png')).pipe(resp) Also, none of this new functionality conflicts with requests previous features, it just expands them. const 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)
}
}) You can still use intermediate proxies, the requests will still follow HTTP forwards, etc. Promises & Async/Await
Several alternative interfaces are provided by the request team, including:
Also, Forms
application/x-www-form-urlencoded (URL-Encoded Forms)URL-encoded forms are simple. 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 Uploads)For const formData = {
// Pass a simple key-value pair
my_field: 'my_value',
// Pass data via Buffers
my_buffer: Buffer.from([1, 2, 3]),
// Pass data via Streams
my_file: fs.createReadStream(__dirname + '/unicycle.jpg'),
// Pass multiple values /w an Array
attachments: [
fs.createReadStream(__dirname + '/attachment1.jpg'),
fs.createReadStream(__dirname + '/attachment2.jpg')
],
// Pass optional meta-data with an 'options' object with style: {value: DATA, options: OPTIONS}
// Use case: for some types of streams, you'll need to provide "file"-related information manually.
// See the `form-data` README for more information about options: https://github.com/form-data/form-data
custom_file: {
value: fs.createReadStream('/dev/urandom'),
options: {
filename: 'topsecret.jpg',
contentType: 'image/jpeg'
}
}
};
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);
}); For advanced cases, you can access the form-data object itself via // NOTE: Advanced use-case, for normal use see 'formData' usage above
const r = request.post('http://service.com/upload', function optionalCallback(err, httpResponse, body) {...})
const form = r.form();
form.append('my_field', 'my_value');
form.append('my_buffer', Buffer.from([1, 2, 3]));
form.append('custom_file', fs.createReadStream(__dirname + '/unicycle.jpg'), {filename: 'unicycle.jpg'}); See the form-data README for more information & examples. multipart/relatedSome variations in different HTTP implementations require a newline/CRLF before, after, or both before and after the boundary of a 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);
}) HTTP Authenticationrequest.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'
}
}); If passed as an option,
The method form takes parameters
Note that you can also specify basic authentication using the URL itself, as
detailed in RFC 1738. Simply pass the
const username = 'username',
password = 'password',
url = 'http://' + username + ':' + password + '@some.server.com';
request({url}, function (error, response, body) {
// Do more stuff with 'body' here
}); Digest authentication is supported, but it only works with Bearer authentication is supported, and is activated when the Custom HTTP HeadersHTTP Headers, such as const request = require('request');
const options = {
url: 'https://api.github.com/repos/request/request',
headers: {
'User-Agent': 'request'
}
};
function callback(error, response, body) {
if (!error && response.statusCode == 200) {
const info = JSON.parse(body);
console.log(info.stargazers_count + " Stars");
console.log(info.forks_count + " Forks");
}
}
request(options, callback); OAuth SigningOAuth version 1.0 is supported. The default signing algorithm is HMAC-SHA1: // OAuth1.0 - 3-legged server side flow (Twitter example)
// step 1
const 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
const req_data =
|
2023-10-27
2022-08-15
2022-08-17
2022-09-23
2022-08-13
请发表评论