How to run node js server on https using self-signed certificate?
I am going to show you example 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 example of node js https express.
we almost run node js project using http as like bellow simple example:
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 example 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
i hope it can help you...
Hardik Savani
I'm a full-stack developer, entrepreneur and owner of ItSolutionstuff.com. I live in India and I love to write tutorials and tips that can help to other artisan. I am a big fan of PHP, Laravel, Angular, Vue, Node, Javascript, JQuery, Codeigniter and Bootstrap from the early stage. I believe in Hardworking and Consistency.
We are Recommending you
- Node JS Mysql Connection Example
- Node JS Multer Rename Uploaded File Example
- Node JS Convert Image File to Base64 String Example
- Node JS Resize Image Before Upload using Multer Sharp
- Multiple File Upload in Node JS using Multer Example
- Node js Express Multiple Image Upload using Multer Example
- File Upload in Node JS using Multer Example
- Node js Express Image Upload using Multer Example
- How to Connect MySQL Database in Node JS?
- Laravel Authenticate User in NodeJS with Socket io using JWT
- How to Upgrade Node.js Version in Ubuntu?