@wilmer.lemke
To use HTTPS connection in Node.js, you can create an HTTPS server using the https
module. Here's a simple example of how you can set up an HTTPS server in Node.js:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
const https = require('https'); const fs = require('fs'); const options = { key: fs.readFileSync('privatekey.pem'), // path to your private key cert: fs.readFileSync('certificate.pem') // path to your certificate }; const server = https.createServer(options, (req, res) => { res.writeHead(200); res.end('Hello World!'); }); server.listen(443, () => { console.log('Server running on port 443'); }); |
In this example, we're creating an HTTPS server using the https.createServer
method and passing in the options
object with the paths to the private key and certificate. You can generate your own self-signed certificate or obtain one from a certificate authority.
Make sure to replace 'privatekey.pem'
and 'certificate.pem'
with the correct paths to your private key and certificate files.
You can then run your Node.js script with node server.js
and access your HTTPS server at https://localhost
or https://127.0.0.1
in a web browser.
Remember that deploying an HTTPS server in a production environment requires obtaining a valid SSL certificate from a trusted certificate authority.