# Request - Simplified HTTP client
[![npm package](https://nodei.co/npm/request.png?downloads=true&downloadRank=true&stars=true)](https://nodei.co/npm/request/)
[![Build status](https://img.shields.io/travis/request/request/master.svg?style=flat-square)](https://travis-ci.org/request/request)
[![Coverage](https://img.shields.io/codecov/c/github/request/request.svg?style=flat-square)](https://codecov.io/github/request/request?branch=master)
[![Coverage](https://img.shields.io/coveralls/request/request.svg?style=flat-square)](https://coveralls.io/r/request/request)
[![Dependency Status](https://img.shields.io/david/request/request.svg?style=flat-square)](https://david-dm.org/request/request)
[![Known Vulnerabilities](https://snyk.io/test/npm/request/badge.svg?style=flat-square)](https://snyk.io/test/npm/request)
[![Gitter](https://img.shields.io/badge/gitter-join_chat-blue.svg?style=flat-square)](https://gitter.im/request/request?utm_source=badge)
## Super simple to use
Request is designed to be the simplest way possible to make http calls. It supports HTTPS and follows redirects by default.
```js
var request = require('request');
request('http://www.google.com', function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body) // Show the HTML for the Google homepage.
}
})
```
## Table of contents
- [Streaming](#streaming)
- [Forms](#forms)
- [HTTP Authentication](#http-authentication)
- [Custom HTTP Headers](#custom-http-headers)
- [OAuth Signing](#oauth-signing)
- [Proxies](#proxies)
- [Unix Domain Sockets](#unix-domain-sockets)
- [TLS/SSL Protocol](#tlsssl-protocol)
- [Support for HAR 1.2](#support-for-har-12)
- [**All Available Options**](#requestoptions-callback)
Request also offers [convenience methods](#convenience-methods) like
`request.defaults` and `request.post`, and there are
lots of [usage examples](#examples) and several
[debugging techniques](#debugging).
---
## Streaming
You can stream any response to a file stream.
```js
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 `application/json`) and use the proper `content-type` in the PUT request (if the headers don’t already provide one).
```js
fs.createReadStream('file.json').pipe(request.put('http://mysite.com/obj.json'))
```
Request can also `pipe` to itself. When doing so, `content-type` and `content-length` are preserved in the PUT headers.
```js
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 `response` argument will be an instance of [http.IncomingMessage](https://nodejs.org/api/http.html#http_class_http_incomingmessage).
```js
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 `error` event before piping:
```js
request
.get('http://mysite.com/doodle.png')
.on('error', function(err) {
console.log(err)
})
.pipe(fs.createWriteStream('doodle.png'))
```
Now let’s get fancy.
```js
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 `pipe()` from `http.ServerRequest` instances, as well as to `http.ServerResponse` instances. The HTTP method, headers, and entity-body data will be sent. Which means that, if you don't really care about security, you can do:
```js
http.createServer(function (req, resp) {
if (req.url === '/doodle.png') {
var x = request('http://mysite.com/doodle.png')
req.pipe(x)
x.pipe(resp)
}
})
```
And since `pipe()` returns the destination stream in ≥ Node 0.5.x you can do one line proxying. :)
```js
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.
```js
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)
}
})
```
You can still use intermediate proxies, the requests will still follow HTTP forwards, etc.
[back to top](#table-of-contents)
---
## Forms
`request` supports `application/x-www-form-urlencoded` and `multipart/form-data` form uploads. For `multipart/related` refer to the `multipart` API.
#### application/x-www-form-urlencoded (URL-Encoded Forms)
URL-encoded forms are simple.
```js
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 `multipart/form-data` we use the [form-data](https://github.com/form-data/form-data) library by [@felixge](https://github.com/felixge). For the most cases, you can pass your upload form data via the `formData` option.
```js
var 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'),
// 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/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);
});
```
For advanced cases, you can access the form-data object itself via `r.form()`. This can be modified until the request is fired on the next cycle of the event-loop. (Note that this calling `form()` will clear the currently set form data for that request.)
```js
// NOTE: Advanced use-case, for normal use see 'formData' usage above
var 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'});
```
See the [form-data README](https://github.com/form-data/form-data) for more information & examples.
#### multipart/related
Some variations in different HTTP implementations require a newline/CRLF before, after, or both before and after the boundary of a `multipart/related` request (using the multipart option). This has been observed in the .NET WebAPI version 4.0. You can turn on a boundary preambleCRLF or postamble by passing them as `true` to your request options.
```js
request({
method: 'PUT',
preambleCRLF: true,
postambleCRLF: true,
uri: 'http://service.com/upload',
multipart: [
程序员Chino的日记
- 粉丝: 3752
- 资源: 5万+
最新资源
- 分时优化机制+碳交易+双层需求响应优化+综合能源系统IES联合低碳优化调度:双碳目标下综合能源系统优化调度采用四个场景控制变量分析调度优化模型(用Matlab+Yalmip+Cplex) 目标函数:系
- 电力电子技术,直流斩波matlab模型图,直流升降压斩波电路,正反激电路,半桥电路,全桥电路,数据已经调试好,可以直接出波形图,可用于电力电子的研究,想要点击加好友加好友我哈~
- 电力电子技术,整流电路matlab模型图,单相半波可控整流电路,单相桥式全控整流电路,三相半波可控整流电路,各个类型的整流电路模型图都有,数据已经调试好,可以直接出波形图,可以用于电力电子的研究
- matlab simulink 风储调频,风电调频,一次调频,四机两区系统,采用频域模型法使得风电渗透率25%,附加惯性控制,储能附加下垂控制,参与系统一次调频,系统频率特性优 有SOC特性 特
- MATLAB路径规划仿真 轨迹规划,船舶轨迹跟踪控制,数学模型基于两轮差速的小车模型,用PID环节对航向角进行控制,迫使小车走向目标,或用PID环节对航向角和距离进行控制,迫使小车走向目标 可自行小车
- matlab代码:Pensim软件 青霉素发酵过程数据集 非线性过程故障检测 工业过程故障检测 -包含了Pensim仿真软件的安装文件以及中文使用手册 很详细的步骤,方便自己生成数据 -包含了两个Ex
- 永磁同步电机电流预测控制 1.采用无差拿电流预测控制器去替传统电流环中的PI控制器,可以提高电流环动态响应; 2.提供算法对应的参考文献和仿真模型,支持技术解答 拿后赠送PMSM控制相关电子资料
- 基于matlab电力系统暂态稳定性参考资料
- 51单片机仿真超声波检测距离?串口上位机显示 ①ADC0832模拟2路超声波A D采集 ②液晶1602显示距离值 ③检测距离定时上报上位机显示 ④检测距离超阈值报警指示灯亮起
- MATLAB机器人仿真 机器人搬运过程仿真,搬运运动过程,仿真过程,末端位移曲线,关节位移速度加速度曲线分析,搬运轨迹,轨迹规划,工作空间分析,多物体搬运,机械臂连杆
- 改进型MPPT算法C源代码仿真,附上实物测试数据
- C#开发项目 C#课本视频 含源码 C#上位系统,SCADA,报警,报表,历史曲线,画面,动画 C# 软件 数据库视频教程 学员管理系统,数据库读写 带案例和源码 带keeper ware Op
- stm32 iap串口升级固件方案,提供上位机调试助手
- 【labview联合cognex框架代码】 【主要包含内容】 1加载vpp,运行vpp,获取vpp结果数据; 2连接相机,相机采图,加载相机采图图片以及显示相机图片; 3读取本地图片加载至
- Labview与三菱FX3u串口通讯,无协议Modbus通讯,读写各种地址,最简单的写法,可读可写,带源码,有通讯报文,PLC通讯参数直接设置,无需另外编程
- 4-20mA采集电路,主控为STM32F103,RS485输出 提供原理图和pcb源文件(AD设计),以及源码,包含ADC采样代码,RS485代码等,带隔离功能
资源上传下载、课程学习等过程中有任何疑问或建议,欢迎提出宝贵意见哦~我们会及时处理!
点击此处反馈