HTTP client.

  
      const http = require('http')
 let request = http.request({
    URL: 'http://localhost:8881/getAppInfo',
    //alternative to URL is host/port/path
    // host: 'localhost', port: '80', path: '/getAppInfo',
    method: 'POST'
    // for peer certificate validation:
    // cert: 'testcert.pem', // Client certificate PEM file
    // CACert: 'cacert.pem', // Certificate authority PEM file
    // key: 'testkey.pem', // Client private key (PEM file)
    // passphrase: '' // optional private key password
 })
 const fileContent = fs.readFileSync('d:/binaryFile.txt') // return ArrayBuffer, since encoding not passed
 // in case of multiple request to the same host better to reuse existed request (up to x30 times faster)
 for (let i = 0; i < 100; i++) {
   request.setPath(`/getAppInfo?nc=${i}`)
   request.write('Add string to response')
   request.write(fileContent, 'base64') // write file content as base64 encoded string
   let response = request.end()
   console.log(response.statusCode)
 }


 const http = require('http')
 const assert = require('assert')
 const DOMParser = require('xmldom').DOMParser
 // To set global proxy settings if client is behind a proxy
 // use http_proxy & no_proxy environment variables
 let resp = http.get('https://synopse.info/fossil/wiki/Synopse+OpenSource')
 // check we are actually behind a proxy
 // assert.ok(resp.headers('via').startsWith('1.1 proxy.main'), 'proxy used');
 let index = resp.read()
 console.log(index);
 // var doc = new DOMParser().parseFromString(index);
 // assert.ok(doc.documentElement.textContent.startsWith('mORMot'), 'got mORMot from mORMot');
  

Classes

Members

# STATUS_CODES : Object.<number, string> static

HTTP status codes.

Methods

# buildURL (urlString, paramsObject) → String static

Add parameters to URL

 http.buildURL('/myMethod', {a: 1, b: "1212"}; // '/myMethod?a=1&b=1212

Arguments:

# get (optionsObject, URLParamsoptObject) → IncomingMessage static

Since most requests are GET requests without bodies, we provides this convenience method. The two difference between this method and http.request() is that

  • it sets the method to GET and calls req.end() automatically
  • can optionally take URLParams Object {paramName: paramValue, ..} and add parameters to request path

Arguments:

# request (optionsObject) → ClientRequest static

Create new HTTP server connection. In case server is behind the proxy - use http_proxy & no_proxy env vars (https_proxy for https on linux)

In case of multiple request to the same host better to reuse existed request. Reusing a request: parse URL once, share the DNS cache, TLS connection and TCP connection (if possible).

Under Unix one request object uses one curl easy handle - see Curl DNS cache

Arguments:
  • options: Object| String
    • URLString

      Service URL in format protocol://host:port/path. Will override useHTTPS, server, host, port and path if passed

    • serverString

      DEPRECATED. Server to connect in format 'host:port' or 'host' in case port == 80.

    • hostString

      Host to connect. If server not specified this value used

    • portString

      Port. Default is 80 for HTTP or 443 for HTTPS

    • path='/'String

      Request path. Defaults to '/'. Should include query string if any. E.G. '/index.html?page=12'

    • method='GET'String

      HTTP method to use for request

    • headersObject.<string, string>

      An object containing request headers

    • useHTTPSBoolean

    • useCompressionBoolean

      Send 'Accept-encoding: gzip' header to server & unzip zipper responses. Default is true

    • keepAliveBoolean

      Use keep Alive HTTP protocol feature if server support it. Default is true

    • sendTimeoutNumber

      Send timeout in ms. Default is 30000 (30 sec)

    • receiveTimeoutNumber

      Receive timeout in ms. Default is 30000 (30 sec)

    • connectTimeoutNumber

      Connect timeout in ms. Default is 30000 (30 sec)

    • strictSSLBoolean

      If passed and sets to false - ignore SSL certificates errors (NOT RECOMMENDED). Recommended way to deal self-signed certificates is to import it into your CA certificate store as described in curl documentation

    • certstring

      Client certificate PEM file

    • CACertstring

      Certificate authority PEM file

    • keystring

      Client private key (PEM file)

    • passphrasestring

      Client private key passphrase

    Either URL string in format protocol://host:port/path or config

  
      const http = require('http')
 // create a request object
 let request = http.request({
    URL: 'http://localhost:8881/getAppInfo',
    //alternative to URL is host/port/path
    // host: 'localhost', port: '80', path: '/getAppInfo',
    method: 'POST'
 })
 // reuse it several times
 for (let i = 0; i < 100; i++) {
   request.setPath(`/getAppInfo?nc=${i}`)
   request.write('Add string to response')
   request.write(fileContent, 'base64') // write file content as base64 encoded string
   let response = request.end()
   console.log(response.statusCode)
 }
  

# setGlobalConnectionDefaults (defaultsObject) static

Override global ( on the http module level) connectiuon defaults.

Settings applied only for newly created {ClientRequest} instances.

     var http = require('http');
     http.setGlobalConnectionDefaults({receiveTimeout: 60000}); // set receive timeout to 60 sec.

Arguments:
  • defaults: Object
    • useHTTPSBoolean

    • useCompressionBoolean

      Send 'Accept-encoding: gzip' header to server & unzip zipper responses. Default is true

    • keepAliveBoolean

      Use keep Alive HTTP protocol feature if server support it. Default is true

    • sendTimeoutNumber

      Send timeout in ms. Default is 30000 (30 sec)

    • receiveTimeoutNumber

      Receive timeout in ms. Default is 30000 (30 sec)

    • connectTimeoutNumber

      Connect timeout in ms. Default is 30000 (30 sec)

    • strictSSLboolean

      Set default value for strictSSL. If sets to false (NOT RECOMMENDED) then SSL certificates errors will be ignored (DANGEROUS). Recommended way to deal self-signed certificates is to import it into your CA certificate store as described in curl documentation

# setGlobalProxyConfiguration (proxyString, bypassoptString) static deprecated

Use http_proxy & no_proxy environment variables. Under windows no_proxy should be semicolon delimited, under linux - comma delimited, see https://curl.se/libcurl/c/CURLOPT_PROXY.html

Configure global ( on the http module level) proxy server in case you can't configure it using either proxycfg.exe -u on Windows XP or netsh winhttp import proxy source=ie for other win version or by pass options.proxyName parameter.

Settings applied only for newly created {ClientRequest} instances.

See for details this MS article

Arguments:
  • proxy: String

    name of the proxy server to use in format [[http|https]://]host[:port] For example 'http://proxy.my.domain:3249'

  • bypass: String| Array

    semicolon delimited list jr array of host names or IP addresses, or host masks or both, that should not be routed through the proxy