Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Node.js https Module

Node.js https Module

Java FileNode.js Built-in Modules


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:


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:

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:


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 a secure proxy service

Security best practices

  1. Always use HTTPS rather than 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

Pass https 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