I'm very new to node and have looked up how to simply set up a node server. I feel like I have it set up correctly but when I go to https://localhost:8080/ it says "Site can't be reached". Nothing is console logged either. I've gone through many similar questions but no solution has helped me yet. I ran npm init and npm install and here is my code:
var Express = require('express');
var Https = require('https');
var Fs = require('fs');
var app = Express();
var port = process.env.EXPRESS_PORT || 8080;
var options = {
key: fs.readFileSync('key.pem'),
cert: fs.readFileSync('cert.pem')
};
console.log("helloo?");
express.createServer(options, function (req, res) {
console.log("hi")
res.writeHead(200);
res.end("hello world\n");
}).listen(8080);
There are many typos in the code, to make it working i had done the changes.
To Create a https server you have to make use of built-in node.js https
module and create a https
server by passing your certificates, as below
GoTo - https://localhost:8080/
Response:
{
message: "this is served in https"
}
var express = require('express');
var https = require('https');
var fs = require('fs');
var app = express();
var port = process.env.EXPRESS_PORT || 8080;
var options = {
key: fs.readFileSync('key.pem'),
cert: fs.readFileSync('cert.pem')
}
console.log("helloo?");
app.get('/', function(req, res) {
res.json({
message: 'this is served in https'
})
})
var secure = https.createServer(options, app); // for express
secure.listen(port, function() {
console.log('localhost started on', port)
})
// for just node server request listener
/* https.createServer(options, (req, res) => {
res.writeHead(200);
res.end('hello world\n');
}).listen(port); */