How to run node js server on https using self-signed certificate?

About Us:

We are from free coder. We are a group of web developers who are passionate about web development. You can learn from us php, laravel, node js, vue js, react js and many other topic on web developement.
we are very happy to help you.
free coder

Today what you are going to learn:

I am going to show you lesson of run node app on https. i explained simply step by step run node js server on https. I’m going to show you about node js https self-signed certificate. We will look at lesson of node js https express.

we almost run node js project using http as like bellow simple lesson:

const http = require('http');

const app = http.createServer(function (req, res) {

res.writeHead(200);

res.write('web-microphone-websocket');

res.end();

});

app.listen(3000, 'localhost', () => {

console.log('Socket server listening on: 3000');

});

but if you need to run this lesson with https link in localhost, then how you can do this. few days ago i had same issue and i must need to run node server with https because of socket io. so i found out solution how to resolve it.

let's see bellow solution:

Solution:

Generate a self-signed certificate

openssl genrsa -out key.pem

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

openssl x509 -req -days 9999 -in csr.pem -signkey key.pem -out cert.pem

rm csr.pem

Update server.js File:

const https = require('https');

const fs = require('fs');

const options = {

key: fs.readFileSync('key.pem'),

cert: fs.readFileSync('cert.pem')

};

const app = https.createServer(options, function (req, res) {

res.writeHead(200);

res.write('web-microphone-websocket');

res.end();

});

app.listen(3000, 'localhost', () => {

console.log('Socket server listening on: 3000');

});

now you can run node file with following command:

node server.js

it will works with https:

https://localhost:3000

thank you very much for following up with me.

Tags

Recent Posts

Related Posts