是什么 ? | : | a simplified HTTP request client. |
开发语言 | : | JavaScript |
源码仓库 | : | https://github.com/request/request |
注意:该包已经被标记为Deprecated
,请使用其他包代替之,比如axios
包管理器 | 安装命令 |
---|---|
npm | npm install request --save |
yarn | yarn add request |
var request = require("request");
GET
请求。
uri
是要请求的地址。
callback
是请求完成的回掉函数。函数原型是function (error, response, body)
示例:
var request = require('request');
request('http://www.baidu.com', function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body) // Show the HTML for the baidu homepage.
}
});
可以是任意请求。
callback
是请求完成的回掉函数。函数原型是function (error, response, body)
options
对象中有下面这些字段:
字段 | 类型 | 说明 |
---|---|---|
uri | String | 要请求的地址 |
method | String | 请求类型,比如GET、POST、PUT、DELETE、HEAD等 |
headers | Object | 设置请求头 |
body | String | 请求体内容 |
json | Boolean | 请求题是否是JSON格式 |
gzip | Boolean | 是否支持gzip压缩,默认是false |
jar | Boolean | 是否支持Cookies,默认是false |
form | Object | 会把form对象自动转成form格式,并经过URL编码。 会自动添加 Content-Type: x-www-form-urlencoded 请求头。 |
formData | Object | 会把formData对象自动转成formData格式。 会自动添加 Content-Type: multipart/form-data 请求头。 |
encoding | String | 字符编码,默认是utf-8,如果是二进制数据,请设置为null |
timeout | Integer | 超时,单位是s |
request({
url: url,
method: "POST",
json: true,
headers: {
"content-type": "application/json",
},
body: JSON.stringify({xx: 'xxx', yy: 'yyy'})
}, function(error, response, body) {
if (!error && response.statusCode == 200) {
// TODO
}
});
request({
url: url,
method: "POST",
form: {xx: 'xxx', yy: 'yyy'}
}, function(error, response, body) {
if (!error && response.statusCode == 200) {
// TODO
}
});
request({
url: url,
method: "POST",
formData: {
// Pass a simple key-value pair
my_field: 'my_value',
// Pass data via Buffers
my_buffer: new Buffer([1, 2, 3]),
// Pass data via Streams
my_file: fs.createReadStream(__dirname + '/unicycle.jpg')
}
}, function(error, response, body) {
if (!error && response.statusCode == 200) {
// TODO
}
});
与request(Object options [, callback])
相同。默认是GET
请求。
与request(Object options [, callback])
唯一的区别是,此方法默认是POST
请求。
与request(Object options [, callback])
唯一的区别是,此方法默认是PUT
请求。
与request(Object options [, callback])
唯一的区别是,此方法默认是DELETE
请求。
与request(Object options [, callback])
唯一的区别是,此方法默认是HEAD
请求。
与request(Object options [, callback])
唯一的区别是,此方法默认是PATCH
请求。
管道,这个用起来和Shell里面的管道很像。
示例1:
request('http://google.com/doodle.png').pipe(fs.createWriteStream('doodle.png'));
示例2:
fs.createReadStream('file.json').pipe(request.put('http://mysite.com/obj.json'));
当获得请求结果时候触发。
示例:
request('http://google.com/img.png')
.on('response', function(response) {
console.log(response.statusCode);
console.log(response.headers['content-type']);
})
.pipe(request.put('http://mysite.com/img.png'));
当出错时候触发。
示例:
request('http://mysite.com/doodle.png')
.on('error', function(err) {
console.log(err);
})
.pipe(fs.createWriteStream('doodle.png'));