httpreq

2019-02-13 admin

httpreq是什么

什么是httpreq,node-httpreq is a node.js library to do HTTP(S) requests the easy way

httpreq使用教程帮助文档

node-httpreq

node-httpreq is a node.js library to do HTTP(S) requests the easy way

Do GET, POST, PUT, PATCH, DELETE, OPTIONS, upload files, use cookies, change headers, …

Install

You can install httpreq using the Node Package Manager (npm):

npm install httpreq

Simple example

var httpreq = require('httpreq');

httpreq.get('http://www.google.com', function (err, res){
  if (err) return console.log(err);

  console.log(res.statusCode);
  console.log(res.headers);
  console.log(res.body);
  console.log(res.cookies);
});

How to use

  • httpreq.get(url, [options], callback)
  • httpreq.post(url, [options], callback)
  • httpreq.put(url, [options], callback)
  • httpreq.delete(url, [options], callback)
  • httpreq.options(url, [options], callback)
  • Uploading files
  • Downloading a binary file
  • Downloading a file directly to disk
  • Sending a custom body
  • Using a http(s) proxy
  • httpreq.doRequest(options, callback)

httpreq.get(url, [options], callback)

<a name=“user-content-get”></a>

Arguments

  • url: The url to connect to. Can be http or https.
  • options: (all are optional) The following options can be passed:
    • parameters: an object of query parameters
    • headers: an object of headers
    • cookies: an array of cookies
    • auth: a string for basic authentication. For example username:password
    • binary: true/false (default: false), if true, res.body will a buffer containing the binary data
    • allowRedirects: (default: true , only with httpreq.get() ), if true, redirects will be followed
    • maxRedirects: (default: 10 ). For example 1 redirect will allow for one normal request and 1 extra redirected request.
    • timeout: (default: none ). Adds a timeout to the http(s) request. Should be in milliseconds.
    • proxy, if you want to pass your request through a http(s) proxy server:
      • host: eg: “192.168.0.1”
      • port: eg: 8888
      • protocol: (default: ‘http’ ) can be ‘http’ or ‘https’
    • rejectUnauthorized: validate certificate for request with HTTPS. More here
  • callback(err, res): A callback function which is called when the request is complete. res contains the headers ( res.headers ), the http status code ( res.statusCode ) and the body ( res.body )

Example without options

var httpreq = require('httpreq');

httpreq.get('http://www.google.com', function (err, res){
  if (err) return console.log(err);

  console.log(res.statusCode);
  console.log(res.headers);
  console.log(res.body);
});

Example with options

var httpreq = require('httpreq');

httpreq.get('http://posttestserver.com/post.php', {
  parameters: {
    name: 'John',
    lastname: 'Doe'
  },
  headers:{
    'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.7; rv:18.0) Gecko/20100101 Firefox/18.0'
  },
  cookies: [
    'token=DGcGUmplWQSjfqEvmu%2BZA%2Fc',
    'id=2'
  ]
}, function (err, res){
  if (err){
    console.log(err);
  }else{
    console.log(res.body);
  }
});

httpreq.post(url, [options], callback)

<a name=“user-content-post”></a>

Arguments

  • url: The url to connect to. Can be http or https.
  • options: (all are optional) The following options can be passed:
    • parameters: an object of post parameters (content-type is set to application/x-www-form-urlencoded; charset=UTF-8)
    • json: if you want to send json directly (content-type is set to application/json)
    • files: an object of files to upload (content-type is set to multipart/form-data; boundary=xxx)
    • body: custom body content you want to send. If used, previous options will be ignored and your custom body will be sent. (content-type will not be set)
    • headers: an object of headers
    • cookies: an array of cookies
    • auth: a string for basic authentication. For example username:password
    • binary: true/false (default: false ), if true, res.body will be a buffer containing the binary data
    • allowRedirects: (default: false ), if true, redirects will be followed
    • maxRedirects: (default: 10 ). For example 1 redirect will allow for one normal request and 1 extra redirected request.
    • encodePostParameters: (default: true ), if true, POST/PUT parameters names will be URL encoded.
    • timeout: (default: none). Adds a timeout to the http(s) request. Should be in milliseconds.
    • proxy, if you want to pass your request through a http(s) proxy server:
      • host: eg: “192.168.0.1”
      • port: eg: 8888
      • protocol: (default: ‘http’ ) can be ‘http’ or ‘https’
    • rejectUnauthorized: validate certificate for request with HTTPS. More here
  • callback(err, res): A callback function which is called when the request is complete. res contains the headers ( res.headers ), the http status code ( res.statusCode ) and the body ( res.body )

Example without extra options

var httpreq = require('httpreq');

httpreq.post('http://posttestserver.com/post.php', {
  parameters: {
    name: 'John',
    lastname: 'Doe'
  }
}, function (err, res){
  if (err){
    console.log(err);
  }else{
    console.log(res.body);
  }
});

Example with options

var httpreq = require('httpreq');

httpreq.post('http://posttestserver.com/post.php', {
  parameters: {
    name: 'John',
    lastname: 'Doe'
  },
  headers:{
    'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.7; rv:18.0) Gecko/20100101 Firefox/18.0'
  },
  cookies: [
    'token=DGcGUmplWQSjfqEvmu%2BZA%2Fc',
    'id=2'
  ]
}, function (err, res){
  if (err){
    console.log(err);
  }else{
    console.log(res.body);
  }
});

httpreq.put(url, [options], callback)

<a name=“user-content-put”></a>

Same options as httpreq.post(url, [options], callback)


<a name=“user-content-delete”>### httpreq.delete(url, [options], callback)</a>

<a name=“user-content-delete”>Same options as</a> httpreq.post(url, [options], callback)


<a name=“user-content-options”>### httpreq.options(url, [options], callback)</a>

<a name=“user-content-options”>Same options as</a> httpreq.get(url, [options], callback) except for the ability to follow redirects.


<a name=“user-content-upload”>### Uploading files

You can still use httpreq.uploadFiles({url: 'url', files: {}}, callback), but it’s easier to just use POST (or PUT):

Example

var httpreq = require('httpreq');

httpreq.post('http://posttestserver.com/upload.php', {
  parameters: {
    name: 'John',
    lastname: 'Doe'
  },
  files:{
    myfile: __dirname + "/testupload.jpg",
    myotherfile: __dirname + "/testupload.jpg"
  }
}, function (err, res){
  if (err) throw err;
});
    • *</a>

<a name=“user-content-upload”></a><a name=“user-content-binary”></a>

Downloading a binary file

To download a binary file, just add binary: true to the options when doing a get or a post.

Example

var httpreq = require('httpreq');

httpreq.get('https://ssl.gstatic.com/gb/images/k1_a31af7ac.png', {binary: true}, function (err, res){
  if (err){
    console.log(err);
  }else{
    fs.writeFile(__dirname + '/test.png', res.body, function (err) {
      if(err)
        console.log("error writing file");
    });
  }
});

<a name=“user-content-download”></a>

Downloading a file directly to disk

To download a file directly to disk, use the download method provided.

Downloading is done using a stream, so the data is not stored in memory and directly saved to file.

Example

var httpreq = require('httpreq');

httpreq.download(
  'https://ssl.gstatic.com/gb/images/k1_a31af7ac.png',
  __dirname + '/test.png'
, function (err, progress){
  if (err) return console.log(err);
  console.log(progress);
}, function (err, res){
  if (err) return console.log(err);
  console.log(res);
});


<a name=“user-content-custombody”></a>

Sending a custom body

Use the body option to send a custom body (eg. an xml post)

Example

var httpreq = require('httpreq');

httpreq.post('http://posttestserver.com/post.php',{
  body: '<?xml version="1.0" encoding="UTF-8"?>',
  headers:{
    'Content-Type': 'text/xml',
  }},
  function (err, res) {
    if (err){
      console.log(err);
    }else{
      console.log(res.body);
    }
  }
);

<a name=“user-content-proxy”></a>

Using a http(s) proxy

Example

var httpreq = require('httpreq');

httpreq.post('http://posttestserver.com/post.php', {
  proxy: {
    host: '10.100.0.126',
    port: 8888
  }
}, function (err, res){
  if (err){
    console.log(err);
  }else{
    console.log(res.body);
  }
});

httpreq.doRequest(options, callback)

<a name=“user-content-dorequest”></a>

httpreq.doRequest is internally used by httpreq.get() and httpreq.post(). You can use this directly. Everything is stays the same as httpreq.get() or httpreq.post() except that the following options MUST be passed:

  • url: the url to post the files to
  • method: ‘GET’, ‘POST’, ‘PUT’ or ‘DELETE’

Donate

If you like this module or you want me to update it faster, feel free to donate. It helps increasing my dedication to fixing bugs :-)

本站文章除注明转载外,均为本站原创或编译。欢迎任何形式的转载,但请务必注明出处。

转载请注明:文章转载自 JavaScript中文网 [https://www.javascriptcn.com]

本文地址:https://www.javascriptcn.com/read-53627.html

文章标题:httpreq

相关文章
Why is it called XMLHttpRequest?
KiL提出了一个问题:Why is it called XMLHttpRequest?,或许与您遇到的问题类似。 回答者gilly3给出了该问题的处理方式: XMLHttpRequest was invented by Microsoft’...
2018-04-21
CORS怎样&apos;预检&apos;一个HttpRequest?
Sunil GargNick提出了一个问题:CORS - How do ‘preflight’ an httprequest?,或许与您遇到的问题类似。 回答者monsur给出了该问题的处理方式: During the preflight ...
2018-03-20
阿贾克斯XMLHttpRequest文件上传
Sedat Başar提出了一个问题:Upload File With Ajax XmlHttpRequest,或许与您遇到的问题类似。 回答者timdream给出了该问题的处理方式: There is no such thing as...
2018-04-06
XmlHttpRequest onprogress interval
Oscar提出了一个问题:XmlHttpRequest onprogress interval,或许与您遇到的问题类似。 回答者Matt Bierner给出了该问题的处理方式: The W3 sets forth the following...
2018-04-14
是会等于发生在XMLHttpRequest = 4?
informatik01Huang提出了一个问题:Is onload equal to readyState==4 in XMLHttpRequest?,或许与您遇到的问题类似。 回答者J. K.给出了该问题的处理方式: It should...
2018-03-16
Why cookies and set-cookie headers can&apos;t be set while making xmlhttprequest using setRequestHeader?
Shubhansh提出了一个问题:Why cookies and set-cookie headers can’t be set while making xmlhttprequest using setRequestHeader?,或许与...
2018-04-26
XMLHttpRequest (Ajax) Error
Nadir MuzaffarMuricula提出了一个问题:XMLHttpRequest (Ajax) Error,或许与您遇到的问题类似。 回答者Nadir Muzaffar给出了该问题的处理方式: So there might be a...
2018-04-19
回到顶部