SSL for Localhost

Yes, you can apply a SSL/TLS certificate for localhost. You can generate a self-signed certificate for localhost using the openssl command-line tool. Here's how:

Install OpenSSL on your machine if it's not already installed.

Open a terminal or command prompt and navigate to the directory where you want to store the certificate files.

Generate a private key:openssl genrsa -out localhost.key 2048

Generate a certificate signing request (CSR):

openssl req -new -key localhost.key -out localhost.csr

When prompted for information, you can enter anything you like, but make sure to specify localhost as the Common Name (CN).

Generate a self-signed certificate:

openssl x509 -req -days 365 -in localhost.csr -signkey localhost.key -out localhost.crt

This will generate a self-signed certificate that is valid for one year.

Start your Node.js server and configure it to use the certificate and private key:

download

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

const options = {
  key: fs.readFileSync('localhost.key'),
  cert: fs.readFileSync('localhost.crt')
};

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

server.listen(8443, () => {
  console.log('Server listening on port 8443');
})

You can then access your Node.js server using the URL https://localhost:8443. Note that your browser may warn you about the self-signed certificate, but you can choose to ignore the warning and proceed anyway.

Keep in mind that self-signed certificates are not trusted by default, so if you want to use SSL/TLS in a production environment, you will need to obtain a trusted certificate from a certificate authority (CA).

it/node/localhost_ssl.txt · 最后更改: 2023-04-23 16:25 由 goldentianya
回到顶部
CC Attribution-Share Alike 4.0 International
Driven by DokuWiki Recent changes RSS feed Valid CSS Valid XHTML 1.0