@herminia_bruen
To use HTTPS with Node.js, you can create an HTTPS server by using the built-in https
module. Here's a step-by-step guide to set up an HTTPS server in Node.js:
1
|
openssl req -nodes -new -x509 -keyout server.key -out server.cert |
This will generate a server.key
and server.cert
file in your current directory.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
const fs = require('fs'); const https = require('https'); const express = require('express'); const app = express(); const options = { key: fs.readFileSync('server.key'), cert: fs.readFileSync('server.cert') }; https.createServer(options, app).listen(443, () => { console.log('HTTPS server running on port 443'); }); app.get('/', (req, res) => { res.send('Hello World!'); }); |
In this example, we first import the necessary modules (fs
, https
, express
). We then create an instance of Express, define the options for the HTTPS server (using the SSL certificate and key we generated earlier), and create an HTTPS server using https.createServer()
. Finally, we listen on port 443 and define a simple route that responds with "Hello World!".
1
|
node server.js |
Your HTTPS server should now be running on port 443. You can access it in your browser by visiting https://localhost
.
Please note that using a self-signed SSL certificate is suitable for development purposes but not recommended for production. In production, you should use a valid SSL certificate from a trusted certificate authority.