I have an https server. It works except for the external script.js. But if the script is internal, it works.
My server.js file:
const https = require("https");
const fs = require("fs");
const options = {
key: fs.readFileSync('server.key'),
cert: fs.readFileSync('server.cert'),
};
https.createServer(options, (req, res) => {
res.writeHead(200);
res.end(fs.readFileSync('index.html'));
}).listen(8000, "localhost");
My index.html file:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<style></style>
</head>
<body>
<button onclick="testFunc();" id="button1"></button>
<script src="script.js"></script>
</body>
</html>
My script.js file:
var button1 = document.getElementById("button1");
alert(); //first alert
function testFunc() {
alert(); //second alert
}
It doesn’t work at all, it doesn’t even show the first alert
I checked the file’s name, and it is correct.
Why doesn’t it work and what should I do to make it work?
>Solution :
Here’s a starting point in order to serve the .js file as well:
https.createServer(options,(req, res) => {
res.writeHead(200);
if ( req.url.endsWith(".js") ){ // If the requested resource ends with .js, then server our script.js file
return res.end(fs.readFileSync('script.js'))
}
// In all other cases, just serve the index.html
res.end(fs.readFileSync('index.html'));
}).listen(8000, "localhost");
Ideally, your controller should be able to serve all sorts of content, with all sorts of filenames (index.html, contact.html, app.js, style.css) based on the extension, .js, .css, .html, etc.
You have to set the appropriate headers as well when serving this content (text/html, text/css, etc.)