HTTPS
HTTPS — это протокол HTTP по TLS/SSL. В Node.js он реализован как отдельный модуль.
Класс: https.Agent
Объект Agent для HTTPS, аналогичный http.Agent. Дополнительную информацию см. в https.request().
Класс: https.Server
Этот класс является подклассом tls.Server и генерирует события аналогично http.Server. Дополнительную информацию см. в http.Server.
server.headersTimeout
-
<число> По умолчанию:
40000
См. http.Server#headersTimeout.
server.setTimeout([msecs][, callback])
server.timeout([msecs])
-
msecs<число> По умолчанию 120000 (2 минуты).
См. http.Server#timeout.
server.keepAliveTimeout
- <число> По умолчанию 5000 (5 секунд).
См. http.Server#keepAliveTimeout.
https.createServer(options[, requestListener])
-
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])
-
callback<Функция>
Подробности см. в http.close().
server.listen(handle[, callback])
server.listen(path[, callback])
server.listen([port][, host][, backlog][, callback])
Подробности см. в http.listen().
https.get(options[, callback])
-
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
Глобальный экземпляр https.Agent для всех запросов HTTPS-клиента.
https.request(options[, callback])
-
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