Mr.D
Mr.D

Reputation: 7893

Express JS, working with HTTPS does not load page

I want to launch my web application with https. I have created self signed key and certificate with this command:

openssl req -newkey rsa:2048 -sha256 -nodes -keyout key.key -x509 -days 365 -out public.pem -subj "/C=US/ST=New York/L=Brooklyn/O=Example Brooklyn Company/CN=my.example.com"

This created to me key.key nad public.pem files.

Now I want to assign them to my express application:

const app = express();
const https = require('https');
const http = require('http');
const fs = require('fs');

app.get('/*', (req, res) => {
        res.send("Hello");
});

const options = {
    key: fs.readFileSync(`${__dirname}/key.key`),  // Path to file with PEM private key
    cert: fs.readFileSync(`${__dirname}/public.pem`)  // Path to file with PEM certificate
};
https.createServer(options, app).listen(443);
http.createServer(app).listen(80);

When I open my my.example.com/ it successfully shows me Hello message text. Howver, when I open it like this https://my.example.com/ my browser does not open this page and shows ERR_SSL_PROTOCOL_ERROR error message.

What did I miss?

Upvotes: 2

Views: 607

Answers (3)

N-Alpr
N-Alpr

Reputation: 334

I believe there is nothing wrong with your code and logic ... if you are using chrome as a browser and it gives such error it is probably because you are using a self signed certificate ...

in case of test there is a way around ... but I recommend you to buy a SSL certificate instead if you can ...

Upvotes: 0

serkan
serkan

Reputation: 7151

Probably your SSL is not correctly created.

Try:

openssl genrsa -out key.pem 2048
openssl req -new -key key.pem -out client.csr
openssl x509 -req -in client.csr -signkey key.pem -out cert.pem

Upvotes: 1

cancelajavi
cancelajavi

Reputation: 151

try to add the follow code, i think is what you need to open by https

var fs = require('fs');
var https = require('https');
var express = require('express');
var key  = fs.readFileSync('sslcert/server.key', 'utf8');
var cert = fs.readFileSync('sslcert/server.crt', 'utf8');

var cred = {key: key, cert: cert};
var app = express();

var serv = https.createServer(cred, app);

serv.listen(443);

I hope this works to you

Upvotes: 2

Related Questions