Enabling HTTPS on express.js

前端 未结 7 897
栀梦
栀梦 2020-11-22 08:44

I\'m trying to get HTTPS working on express.js for node, and I can\'t figure it out.

This is my app.js code.

var express = require(\'exp         


        
7条回答
  •  囚心锁ツ
    2020-11-22 09:31

    First, you need to create selfsigned.key and selfsigned.crt files. Go to Create a Self-Signed SSL Certificate Or do following steps.

    Go to the terminal and run the following command.

    sudo openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout ./selfsigned.key -out selfsigned.crt

    • After that put the following information
    • Country Name (2 letter code) [AU]: US
    • State or Province Name (full name) [Some-State]: NY
    • Locality Name (eg, city) []:NY
    • Organization Name (eg, company) [Internet Widgits Pty Ltd]: xyz (Your - Organization)
    • Organizational Unit Name (eg, section) []: xyz (Your Unit Name)
    • Common Name (e.g. server FQDN or YOUR name) []: www.xyz.com (Your URL)
    • Email Address []: Your email

    After creation adds key & cert file in your code, and pass the options to the server.

    const express = require('express');
    const https = require('https');
    const fs = require('fs');
    const port = 3000;
    
    var key = fs.readFileSync(__dirname + '/../certs/selfsigned.key');
    var cert = fs.readFileSync(__dirname + '/../certs/selfsigned.crt');
    var options = {
      key: key,
      cert: cert
    };
    
    app = express()
    app.get('/', (req, res) => {
       res.send('Now using https..');
    });
    
    var server = https.createServer(options, app);
    
    server.listen(port, () => {
      console.log("server starting on port : " + port)
    });
    
    • Finally run your application using https.

    More information https://github.com/sagardere/set-up-SSL-in-nodejs

提交回复
热议问题