Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

External script.js doesn't run in html

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<!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.)

Reference

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading