user3697220
user3697220

Reputation: 131

Server HTTPS on node.js doesn't work

I'm trying to create an HTTPS server. I have generated privatekey.pem and certicate.pem with Cygwin64 following these instructions:

openssl genrsa -out privatekey.pem 1024
openssl req -new -key privatekey.pem -out certrequest.csr
openssl x509 -req -in certrequest.csr -signkey privatekey.pem -out certificate.pem

while my server code is this:

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

var options = {
  key: fs.readFileSync('privatekey.pem'),
  cert: fs.readFileSync('certificate.pem')
};

https.createServer(options, function (req, res) {
  res.writeHead(200);
  res.end("hello world\n");
}).listen(8001);

When i try to connect to address https://localhost:8001, the web page is not available. Can anyone help me?

Upvotes: 8

Views: 9967

Answers (1)

rajeshwerkushwaha
rajeshwerkushwaha

Reputation: 311

Your code is absolutely working fine. I have tested it in my localhost. I think the issue is with your key generation. Try to generate once again the keys and run your server. I hope it will work.

Note: The certificate you are generating, will work only in localhost. So do not try this in any online IDE(like codio.com, koding.com, cloud9.com etc). If you want to do to you have to purchase the SSL Certificate from the company like Verysign.

OR

If not try the below code.

Step 1: Open your terminal and run the following command to generate private key file 'key.pem'.

$ openssl genrsa 1024 > key.pem

Step 2: Now run the following command to generate SSL Certificate file 'key-cert.pem'.

$ openssl req -x509 -new -key key.pem > key-cert.pem

Step 3: Now write the 'server.js' file with the following content.

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

var options = {
  key: fs.readFileSync('key.pem'),
  cert: fs.readFileSync('key-cert.pem')
};

https.createServer(options, function (req, res) {
  res.writeHead(200);
  res.end("hello world\n");
}).listen(8001);

Step 4: Now run the server file using following command.

$ node server.js

Step 5: Now in the browser hit the url 'https://localhost:8001' and accept the certificate and you will see the 'hello world' message on the page.

Upvotes: 6

Related Questions