Home  >  Article  >  Web Front-end  >  How to Create an HTTPS Server with SSL Certificate in Node.js?

How to Create an HTTPS Server with SSL Certificate in Node.js?

Barbara Streisand
Barbara StreisandOriginal
2024-10-23 20:42:02301browse

How to Create an HTTPS Server with SSL Certificate in Node.js?

Creating an HTTPS Server in Node.js

In Node.js, establishing an HTTPS server involves utilizing the Express framework and the 'https' module. Here's a detailed response to the question:

Given an SSL key and certificate, how does one create an HTTPS service?

Solution:

The Express API documentation provides clear instructions on how to achieve this. Additionally, the following steps will assist you in creating a self-signed certificate:

var express = require('express');
var https = require('https');
var http = require('http');
var fs = require('fs');

// Import the certificate and key
const options = {
  key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'),
  cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem')
};

// Initialize the Express app
const app = express();

// Create HTTP and HTTPS servers
const httpsServer = https.createServer(options, app);
const httpServer = http.createServer(app);

// Set up the HTTP and HTTPS ports
httpsServer.listen(443);
httpServer.listen(80);

By following these steps, you can successfully create an HTTPS server in Node.js using the provided SSL key and certificate.

The above is the detailed content of How to Create an HTTPS Server with SSL Certificate in Node.js?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn