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?
2
Answers
Here’s a starting point in order to serve the .js file as well:
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.)
Reference
My advice is to use
express
from thenpm
package family for creating a server inNodeJS
. Check out that linkFirst, you need to install the package:
Then just import the package and use it as shown below
File
server.js
:In the code above I have created a fully working server that returns the
index.html
file when accessinghttps://localhost:8000/
. At the same file level as theserver.js
file, you need to create a folder calledpublic
and in there you need to put allCSS
andJS
files you import in theHTML
files you have.Now some advice from me for a cleaner code and best practices:
.listen()
on that variablefs
it is best to read all of theHTML
files at the top of the file and save the values in a variable that can later be used everywhere. Keep in mind thatNodeJS
is asingle-thread
compiler and what that means is when you read a file with.readFileSync()
this stops everything else before finishing reading the file. This will make the server slow with more users on it (best practice is to never usesync
functions on a server).