Node.js https Module

Java FileNode.js Built-in Modules


httpsIt is a core built-in module of Node.js, used to create HTTPS servers and clients, handling secure HTTP requests and responses. HTTPS is a secure transmission protocol encrypted via SSL/TLS on top of HTTP.

andhttpCompared with the module,httpsthe main differences are:

  • Uses SSL/TLS to encrypt communication
  • The default port is 443 instead of 80
  • A digital certificate is required to verify the server's identity

Core Features

Create HTTPS Server

Example

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

// Read certificate files
const options = {
  key: fs.readFileSync('server-key.pem'),
  cert: fs.readFileSync('server-cert.pem')
};

// Create HTTPS server
const server = https.createServer(options, (req, res) => {
  res.writeHead(200);
  res.end('Hello HTTPS World!');
});

server.listen(443, () => {
  console.log('HTTPS server running on port 443');
});

Make HTTPS Request

Example

const https = require('https');

https.get('https://example.com', (res) => {
  console.log('Status code:', res.statusCode);
  console.log('Request headers:', res.headers);

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

Key Concepts

SSL/TLS Certificates

An HTTPS server requires the following certificate files:

  • key: Private key file (.key or .pem)
  • cert: Public key certificate (.crt or .pem)
  • Optionalca: Intermediate certificate of the certificate authority (CA)

You can use OpenSSL to generate self-signed certificates for development and testing:

Example

openssl req -x509 -newkey rsa:4096 -keyout key.pem -out cert.pem -days 365

Requests and Responses

httpsThe module's API ishttpalmost the same as the module; the main objects include:

  • https.Server: HTTPS server class
  • https.request(): Make HTTPS requests
  • https.get(): Convenience method for making GET requests

Practical Application Scenarios

  1. Secure Web Services: Build Web applications that require encrypted transmission
  2. API Calls: Securely call third-party HTTPS APIs
  3. Microservice Communication: Secure communication between services
  4. Proxy Server: Build secure proxy services

Security Best Practices

  1. Always use HTTPS instead of HTTP to transmit sensitive data
  2. Regularly update SSL/TLS certificates
  3. Use strong cipher suites and secure protocol versions
  4. Consider using free certificate authorities such as Let's Encrypt
  5. Avoid using self-signed certificates in production environments

Throughhttpsthe module, Node.js developers can easily build secure network applications and services, protecting the privacy and integrity of data during transmission.

Java FileNode.js Built-in Modules

Other Extensions