Spec-Zone.ru › Node.js 6 LTS

HTTPS

Стабильность: 2 - Стабильно

HTTPS — это протокол HTTP по TLS/SSL. В Node.js он реализован как отдельный модуль.

Класс: https.Agent

Добавлен в: v0.4.5

Объект Agent для HTTPS, аналогичный http.Agent. Дополнительную информацию см. в https.request().

Класс: https.Server

Добавлен в: v0.3.4

Этот класс является подклассом tls.Server и генерирует события аналогично http.Server. Дополнительную информацию см. в http.Server.

server.headersTimeout

  • <число> По умолчанию: 40000

См. http.Server#headersTimeout.

server.setTimeout([msecs][, callback])

Добавлен в: v0.11.2
  • msecs <число> По умолчанию 120000 (2 минуты).
  • callback <Функция>

См. http.Server#setTimeout().

server.timeout([msecs])

Добавлен в: v0.11.2
  • msecs <число> По умолчанию 120000 (2 минуты).

См. http.Server#timeout.

server.keepAliveTimeout

Добавлен в: v6.17.0
  • <число> По умолчанию 5000 (5 секунд).

См. http.Server#keepAliveTimeout.

https.createServer(options[, requestListener])

Добавлен в: v0.3.4
  • options <Объект> Принимает options из tls.createServer() и tls.createSecureContext().
  • requestListener <Функция> Обработчик для события request.

Пример:

// curl -k https://localhost:8000/
const https = require('https');
const fs = require('fs');

const options = {
  key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'),
  cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem')
};

https.createServer(options, (req, res) => {
  res.writeHead(200);
  res.end('hello world\n');
}).listen(8000);

Или

const https = require('https');
const fs = require('fs');

const options = {
  pfx: fs.readFileSync('test/fixtures/test_cert.pfx'),
  passphrase: 'sample'
};

https.createServer(options, (req, res) => {
  res.writeHead(200);
  res.end('hello world\n');
}).listen(8000);

server.close([callback])

Добавлен в: v0.1.90
  • callback <Функция>

Подробности см. в http.close().

server.listen(handle[, callback])

  • handle <Объект>
  • callback <Функция>

server.listen(path[, callback])

  • path <строка>
  • callback <Функция>

server.listen([port][, host][, backlog][, callback])

  • port <число>
  • hostname <строка>
  • backlog <число>
  • callback <Функция>

Подробности см. в http.listen().

https.get(options[, callback])

Добавлен в: v0.3.6
  • options <Объект> | <строка> Принимает те же options что и https.request(), с method всегда установленным в GET.
  • callback <Функция>

Аналогично http.get(), но для HTTPS.

options может быть объектом или строкой. Если options — строка, она автоматически разбирается с помощью url.parse().

Пример:

const https = require('https');

https.get('https://encrypted.google.com/', (res) => {
  console.log('statusCode:', res.statusCode);
  console.log('headers:', res.headers);

  res.on('data', (d) => {
    process.stdout.write(d);
  });

}).on('error', (e) => {
  console.error(e);
});

https.globalAgent

Добавлен в: v0.5.9

Глобальный экземпляр https.Agent для всех запросов HTTPS-клиента.

https.request(options[, callback])

Добавлен в: v0.3.6
  • options <Объект> | <строка> Принимает все options из http.request() с некоторыми отличиями в значениях по умолчанию:
    • protocol По умолчанию https:
    • port По умолчанию 443.
    • agent По умолчанию https.globalAgent.
  • callback <Функция>

Отправляет запрос на защищённый веб-сервер.

Также принимаются следующие options из tls.connect() при использовании настраиваемого Agent: pfx, key, passphrase, cert, ca, ciphers, rejectUnauthorized, secureProtocol, servername

options может быть объектом или строкой. Если options — строка, она автоматически разбирается с помощью url.parse().

Пример:

const https = require('https');

const options = {
  hostname: 'encrypted.google.com',
  port: 443,
  path: '/',
  method: 'GET'
};

const req = https.request(options, (res) => {
  console.log('statusCode:', res.statusCode);
  console.log('headers:', res.headers);

  res.on('data', (d) => {
    process.stdout.write(d);
  });
});

req.on('error', (e) => {
  console.error(e);
});
req.end();

Пример использования параметров из tls.connect():

const options = {
  hostname: 'encrypted.google.com',
  port: 443,
  path: '/',
  method: 'GET',
  key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'),
  cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem')
};
options.agent = new https.Agent(options);

const req = https.request(options, (res) => {
  // ...
});

Альтернативно, откажитесь от кэширования соединений, не используя Agent.

Пример:

const options = {
  hostname: 'encrypted.google.com',
  port: 443,
  path: '/',
  method: 'GET',
  key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'),
  cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem'),
  agent: false
};

const req = https.request(options, (res) => {
  // ...
});

© Joyent, Inc. and other Node contributors
Licensed under the MIT License.
Node.js is a trademark of Joyent, Inc. and is used with its permission.
We are not endorsed by or affiliated with Joyent.
https://nodejs.org/dist/latest-v6.x/docs/api/https.html

Spec-Zone.ru

Настройки Оффлайн Что нового Помощь О нас
Spec-Zone .ru
спецификации, руководства, описания, API