Node.js https Module
https is a built-in core module of Node.js, used to create HTTPS servers and clients, and handle secure HTTP requests and responses. HTTPS is a secure transmission protocol based on HTTP and encrypted via the SSL/TLS protocol.
The difference between http Compared with the module,https the main differences of the module are:
- Uses SSL/TLS encrypted communication
- The default port is 443 instead of 80
- Requires a digital certificate to verify the server's identity
Core Features
Create an HTTPS server
Example
const
https
=
require
(
'https'
)
;
const
fs
=
require
(
'fs'
)
;
// Read the certificate file
const
options
=
{
key
:
fs.
readFileSync
(
'server-key.pem'
)
,
cert
:
fs.
readFileSync
(
'server-cert.pem'
)
}
;
// Create an 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 an 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)- Optional
ca: intermediate certificate from the Certificate Authority (CA)
You can use OpenSSL to generate a self-signed certificate for development and testing:
Example
openssl req
-x509
-newkey
rsa:
4096
-keyout
key.pem
-out
cert.pem
-days
365
Requests and Responses
https The API of the module is http almost the same as the module, with the following main objects:
https.Server: HTTPS server classhttps.request(): Make an HTTPS requesthttps.get(): A shortcut method for making a GET request
Practical Application Scenarios
- Secure Web Services: Build web applications that require encrypted transmission
- API Calls: Securely call third-party HTTPS APIs
- Microservice Communication: Secure communication between services
- Proxy Server: Build a secure proxy service
Security best practices
- Always use HTTPS rather than HTTP to transmit sensitive data
- Regularly update SSL/TLS certificates
- Use strong cipher suites and secure protocol versions
- Consider using free certificate authorities such as Let's Encrypt
- Avoid using self-signed certificates in production environments
Pass https module, Node.js developers can easily build secure network applications and services, protecting the privacy and integrity of data during transmission.
Node.js Built-in Modules