# 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万+
最新资源
- CRUISE纯电动车仿真模型,实际项目base模型 simulink DLL联合仿真,基于标定的map模型,适用于vcu+esp实现能量回收的项目 关于模型: 1.策略是用64位软件编译的,如果模
- 全套S7-1200一拖三恒压供水程序样例+PID样例+触摸屏样例 34 1、此程序采用S7-1200PLC和KTP1000PN触摸屏人机执行PID控制变频器实现恒压供水. 包括plc程序,触摸屏
- SOMBP预测模型,数据可以多输入单输出做拟合预测模型,直接替数据就可以使用,程序内有注释,可学习性强,可除两种拟合预测图,以及多种模型评价指标
- Matlab simulink仿真的直流配电网,图2为下垂控制仿真模型,图3为流器(VSC)仿真模型,有这完美的电压与电流波形,两种VSC的有功功率与下垂控制的有功功率,输出电压波形
- 西门子1500PLC机器人焊接程序(西门子PLC+西门子触摸屏) 触摸屏:TP1500 精智面板 PLC:CPU 1516F-3 PN DP 程序:梯形图+SCL PS:注释详细 1台西门子1500P
- 基于WinCE6.0 + Visual Studio2008(VC++开发) + Googol固高codesys运动控制器,开发的示教控制系统 操作者可以通过简单的选择、参数设定而实现相对、绝对定位
- 恒压供水plc程序,1拖1十1辅泵,1拖2十1至1拖4十1辅泵,水箱,无负压通用,有完整的图纸和注释,使用三菱FX1N.2N系列plc十fx0n3a模拟量十昆仑通态tpc7062触摸屏,适合参考学习
- 量产大厂成熟FOC电机控制方案,代码 大厂成熟Foc电机控 码,有原理图,pcb 可用于电动自行车,滑板车,电机Foc控制等 大厂成熟方案,直接可用,,不是一般的普通代码可比的 代码基于st
- 基于遗传算法的车间调度 已知加工时间,如何确定加工顺序和工件分配情况,使得最大完工时间极小化 内涵详细的代码注释
- matlab模型降级算法,传递函数降阶算法 电机控制,并网控制,四旋翼控制等 高阶传递函数进行降级阶处理,逼近传递函数n阶矩阵的距,实现模型降级,操作简单 (有arnolid算法、lanczos
- starccm+电池包热管理-新能源汽车电池包共轭传热仿真 可查學習模型如何搭建,几何清理网格划分,學習重要分析参数如何设置 内容: 0.电池包热管理基础知识讲解,电芯发热机理,电池热管理系统介绍
- 药厂BMS、EMS PLC程序,含触摸屏程序,很有借鉴意义 大型药厂在运行程序; 控制器用的是西门子1500; 里面运用的结构化编程思路很值得借鉴; 药厂各种控制模式; 控温控湿控压; 里面包含数据滤
- 西门子v90伺服与G120 变频pLC控制程序博途Ⅴ14 V15 V16 Ⅴ17版 Cpu为1217,触摸屏为KTp700,4台v90和两台G120釆用PN通讯模式,自动上料机程序 有视屏教程
- matlab simulink 二次调频,4机2区系统二次调频,用模型方法对四机两区系统进行了二次调频分析,有以下两点内容, 1.传统同步机二次调频特性分析 2.用水电风电替系统同步机之后的调频特性
- Matlab使用CNN卷积神经网络进行图像分类,使用了猫狗大战数据集的4000个图像(2000猫2000狗),分为猫狗两个类别 也可以改成多分类 注释详细,可直接运行,可以直接成自己的数据,源代码
- Matlab代码模板,图像处理,色彩补偿,色彩平衡,显示连通分量数量,自动阈值分割图像,人脸数据集的主成分分析,利用最小距离分类器分类3种植物,
资源上传下载、课程学习等过程中有任何疑问或建议,欢迎提出宝贵意见哦~我们会及时处理!
点击此处反馈