HTTPS
HTTPS — это протокол HTTP поверх TLS/SSL. В Node.js он реализован как отдельный модуль.
Класс: https.Agent
Объект Agent для HTTPS, аналогичный http.Agent. Дополнительную информацию см. в https.request().
Класс: https.Server
Этот класс является подклассом tls.Server и генерирует события так же, как и http.Server. Дополнительную информацию см. в http.Server.
server.close([callback])
-
callback<Функция>
Подробности см. в server.close() модуля HTTP.
server.listen()
Запускает HTTPS-сервер, прослушивающий зашифрованные подключения. Этот метод идентичен server.listen() из net.Server.
server.headersTimeout
-
<число> По умолчанию:
40000
См. http.Server#headersTimeout.
server.setTimeout([msecs][, callback])
server.timeout
-
<число> По умолчанию:
120000(2 минуты)
См. http.Server#timeout.
server.keepAliveTimeout
-
<число> По умолчанию:
5000(5 секунд)
См. http.Server#keepAliveTimeout.
https.createServer([options][, requestListener])
-
options<Объект> Принимаетoptionsизtls.createServer(),tls.createSecureContext()иhttp.createServer(). -
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);
https.get(options[, callback])
-
options<Объект> | <строка> | <URL> Принимает те жеoptionsпараметры, что иhttps.request(), сmethodвсегда установленным в значениеGET. -
callback<Функция>
Аналогично http.get(), но для HTTPS.
options может быть объектом, строкой или объектом URL. Если options — строка, она автоматически парсится с помощью url.parse(). Если это объект URL, он автоматически преобразуется в обычный options объект.
Пример:
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
Глобальный экземпляр https.Agent для всех HTTPS-клиентских запросов.
https.request(options[, callback])
-
options<Объект> | <строка> | <URL> Принимает все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 может быть объектом, строкой или объектом URL. Если options — строка, она автоматически парсится с помощью url.parse(). Если это объект URL, он автоматически преобразуется в обычный options объект.
Пример:
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) => {
// ...
});
Пример использования URL как options:
const { URL } = require('url');
const options = new URL('https://abc:xyz@example.com');
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-v8.x/docs/api/https.html