# 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.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)
[![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](http://nodejs.org/api/http.html#http_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/felixge/node-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/felixge/node-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/felixge/node-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: [
{
'content-type': 'application/json',
body: JSON.stringify({foo: 'bar', _attachments: {'message.txt': {follo
程序员Chino的日记
- 粉丝: 3743
- 资源: 5万+
最新资源
- 2kw, 2.4kw, 3.6kw全系列双向储能电源解决方案,c语言源代码仿真,电池充电1200w, 离网逆变2kw,并网逆变2kw,全程工作最优模式
- 基于comsol的高频振动击碎微颗粒的乳化仿真 采用较高频率振动,击碎微颗粒,达到均质或其他目的 本模型计算了整个击碎的微观过程 通过comsol的流固耦合和两相流进行计算,合理的设置调试后,可以
- 基于范围选择的多目标进化算法,多目标优化算法程序代码,PESA-II,采用pesa2求解多目标优化问题,求解得到pareto最优解 基于matlab的.m程序,采用模块化编程,便于修改,注释率高,易
- 松下FP-XH PLC程序 旋转上下料机 松下FP-XH系列PLC程序,等输入输出模块 四轴轴脉冲控制伺服电机,绝对定位,真空报警、正负极限位报警、气缸报警,位置控制模式采用数据表设置模式
- 汽车制动盘热仿真分析matlab源代码 可用于不同材料,不同体积汽车制动盘的热性能仿真对比分析 适用于赛道刹车盘热工况,AMS工况热容量仿真分析等
- 转动惯量离线辨识算法仿真 1.模型简介 模型为永磁同步电机伺服控制仿真,采用Matlab R2018a Simulink搭建 模型内主要包含DC直流电压源、三相逆变器、永磁同步电机、采样模块、SVP
- 三菱FX5U系列程序 三菱FX5U程序,FX5U-80MT ES,FX5-16ET ES-H*4共12轴运动控制,FX5-32ET ES等输入输出模块 尺寸检测机 轴JOG,回原点,绝对定
- MATLAB代码:考虑电动汽车负荷随机性的蓄电池容量优化配置 关键词:蓄电池容量优化配置 储能优化配置 中长期配置 并网波动性 参考文档:《不确定环境下并网型光储微电网的容量规划》考虑电动汽车
- MATLAB代码:基于改进萤火虫算法的分布式电源选址定容-IEEE33节点 关键词:改进萤火虫算法 选址定容 分布式电源 参考文档:《基于改进萤火虫算法的分布式电源的选址和定容-史吏》基本复现
- MATLAB代码:基于NSGA-II的风光水多能互补协调优化调度 关键词:NSGA-II算法 多目标优化 水电-光伏多能互补 参考文档:《店主自写文档》基本复现; 仿真平台:MATLAB 主要
- 基于改进鲸鱼优化算法的冷热电联供微网多时间尺度优化调度模型 关键词:改进鲸鱼算法 冷热电联供微网 优化调度 多时间尺度 容量配置 主要内容:代码主要做的是一个冷热电联供微网的优化调度问题,为了优化其
- MATLAB代码:基于遗传算法的电动汽车有序充放电优化 关键词:遗传算法 电动汽车 有序充电 优化调度 参考文档:《精英自适应混合遗传算法及其实现-江建》 MATLAB 利用遗传算法对电动汽车有序
- MATLAB代码:基于MATLAB的三母线高斯赛德尔潮流分析计算 关键词:潮流计算 电力系统 高斯赛德尔迭代法 MATLAB 参考文献+自制详细实验文档 仿真平台:MATLAB 主要内容:潮流计算是判
- STM32 EtherCAT EtherCAT通信,量产伺服驱动器 采用STM32作为主控 支持ethercat从站IO,模拟输入 已实现底层驱动,中断处理,数据通信 包括原理图,源代码,说明文档 已
- 西门子smart 200 rtu方式通讯四台三菱E700变频器资料 硬件:smart plc.三菱E700变频器,mcgs触摸屏(电脑仿真也可) 功能:指针写法,通过modbus rtu方式,实现对
- 模块化多电平变器MMC的pi 无源控制 滑模控制策略实现(交流7kV-直流20kV整流)仿真,三个仿真均为外环pi控制输出稳压20kV,内环分别采用pi 无源控制 滑模控制 单桥臂二十子模块(子模块
资源上传下载、课程学习等过程中有任何疑问或建议,欢迎提出宝贵意见哦~我们会及时处理!
点击此处反馈