skip to Main Content

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


  1. 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

    Login or Signup to reply.
  2. My advice is to use express from the npm package family for creating a server in NodeJS. Check out that link

    First, you need to install the package:

    npm install express
    

    Then just import the package and use it as shown below
    File server.js:

    const express = require("express");
    const https = require("https");
    const fs = require("fs");
    
    const indexHTML = fs.readFileSync("index.html");
    
    const options = {
      key: fs.readFileSync("server.key"),
      cert: fs.readFileSync("server.cert")
    };
    
    const app = express();
    const server = https.createServer(options, app);
    
    app.use(express.static("public"));
    
    app.get("/", (req, res) => {
      res.status(200).send(indexHTML);
    })
    
    server.listen(8000, () => {
      console.log("Server is listening at port 8000")
    })
    

    In the code above I have created a fully working server that returns the index.html file when accessing https://localhost:8000/. At the same file level as the server.js file, you need to create a folder called public and in there you need to put all CSS and JS files you import in the HTML files you have.

    Now some advice from me for a cleaner code and best practices:

    • When listening on the server, it is better to have it in a separate place. That means you need to save the server in a variable and then .listen() on that variable
    • When using fs it is best to read all of the HTML files at the top of the file and save the values in a variable that can later be used everywhere. Keep in mind that NodeJS is a single-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 use sync functions on a server).
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search