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 (url: String, params: Object) → String static
Add parameters to URL
http.buildURL('/myMethod', {a: 1, b: "1212"}; // '/myMethod?a=1&b=1212
# get (options: Object, URLParamsopt: Object) → 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:
options: ObjectRequest options as described in http.request
URLParams: Objectoptional parameters to add to options.path
# request (options: Object) → 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| StringURL: StringService URL in format
protocol://host:port/path. Will overrideuseHTTPS,server,host,portandpathif passedserver: StringDEPRECATED. Server to connect in format 'host:port' or 'host' in case port == 80.
host: StringHost to connect. If
servernot specified this value usedport: StringPort. Default is 80 for HTTP or 443 for HTTPS
path='/': StringRequest path. Defaults to '/'. Should include query string if any. E.G. '/index.html?page=12'
method='GET': StringHTTP method to use for request
headers: Object.<string, string>An object containing request headers
useHTTPS: BooleanuseCompression: BooleanSend 'Accept-encoding: gzip' header to server & unzip zipper responses. Default is true
keepAlive: BooleanUse keep Alive HTTP protocol feature if server support it. Default is true
sendTimeout: NumberSend timeout in ms. Default is 30000 (30 sec)
receiveTimeout: NumberReceive timeout in ms. Default is 30000 (30 sec)
connectTimeout: NumberConnect timeout in ms. Default is 30000 (30 sec)
strictSSL: BooleanIf 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 documentationcert: stringClient certificate PEM file
CACert: stringCertificate authority PEM file
key: stringClient private key (PEM file)
passphrase: stringClient private key passphrase
Either URL string in format
protocol://host:port/pathor 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 (defaults: Object) 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: ObjectuseHTTPS: BooleanuseCompression: BooleanSend 'Accept-encoding: gzip' header to server & unzip zipper responses. Default is
truekeepAlive: BooleanUse keep Alive HTTP protocol feature if server support it. Default is
truesendTimeout: NumberSend timeout in ms. Default is 30000 (30 sec)
receiveTimeout: NumberReceive timeout in ms. Default is 30000 (30 sec)
connectTimeout: NumberConnect timeout in ms. Default is 30000 (30 sec)
strictSSL: booleanSet 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 (proxy: String, bypassopt: String) 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
